Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use cancancan?

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)?

like image 462
vveare138 Avatar asked Dec 08 '14 11:12

vveare138


2 Answers

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.

  • as a Role model,
  • Rails enum,
  • as suggested here,
  • as a string attribute of 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
like image 90
blelump Avatar answered Oct 17 '22 16:10

blelump


You can refer following rails cast http://railscasts.com/episodes/192-authorization-with-cancan

like image 27
Rubyman Avatar answered Oct 17 '22 17:10

Rubyman