Answer the question
In order to leave comments, you need to log in
How to use multiple roles in a cancan?
Hello guys. Such a question: I want to use three roles in the application admin, moder and client. The admin can do everything, the moderator can rub comments and posts, and the client can create posts, read and edit his comments. I used cancancan, here is the ability class
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.admin?
can :manage, :all
elsif user.moderator?
can :manage, Post, Comment
elsif user.client?
can :create, Post
can [:update, :destroy], Comment, user_id: user.id
else
can :read, :all
end
end
end
Answer the question
In order to leave comments, you need to log in
Obviously, explicitly handle this situation:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.persisted?
if user.admin?
can :manage, :all
elsif user.moderator?
can :manage, Post, Comment
elsif user.client?
can :create, Post
can [:update, :destroy], Comment, user_id: user.id
end
end
can :read, :all
end
end
Try to explicitly disable:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.admin?
can :manage, :all
elsif user.moderator?
can :manage, Post, Comment
elsif user.client?
can :create, Post
can [:update, :destroy], Comment, user_id: user.id
else
cannot :create, Post
can :read, :all
end
end
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question