I want to give rights to users in my rails app. I have 'admin' who can create, update and delete all posts and comments, 'user' who can create and update only his own comments, and 'guest' who can do none of these. For this I use the gems 'devise' and 'cancancan'. I understand the 'devise' gem, but I don't understand 'cancancan'.
In the class ability.rb, how can I write rights for these users (admin, user, guest)?
Cancancan
lets you only define permissions for given context. This context might be a user role which is not a part of cancancan
and hence roles have to be defined by yourself.
There are various ways to define user role, e.g.
Role
model,User
model. It all depends of the use case. An example of how to define abilities can be found here. In your case, it would look like:
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.reviewer? #Just a logged user
can :manage, Comment, { owner_id: user.id }
elsif user.admin?
can :manage, :all
end
end
end
class User < ActiveRecord::Base
enum role: [ :reviewer, :admin ]
end
You can refer following rails cast http://railscasts.com/episodes/192-authorization-with-cancan
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With