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 ofcancancan
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:
If you are going to use Roles, consider the Canard gem (https://github.com/james2m/canard) which combines CanCanCan with RoleModel (https://github.com/martinrehfeld/role_model). This gives you a well organized way of stipulating roles and their abilities
For example, if you have a user model, you would set the roles as follows:
Then you can create Ability files for each role, including a base User (not assigned any roles) and Guest (not logged in)
The above will allow a user to update their own information but will not allow them to delete themselves. They also will not have access to any other user record.
You can refer following rails cast http://railscasts.com/episodes/192-authorization-with-cancan