How to use cancancan?

I want to grant rights to users in my rails application. I have an “administrator” who can create, update and delete all posts and comments, a “user” who can create and update only their own comments and a “guest” who cannot do anything. For this, I use "invent gems" and "cancancan." I understand the "inventive" stone, but I do not understand the "cancancan".

In the capability.rb class, how can I write permissions for these users (admin, user, guest)?

+4
source share
3 answers

Cancancanallows you to define permissions for a given context. This context may be a user role that is not part Cancancan, and therefore the roles must be defined by themselves.

There are various ways to define a user role, for example.

  • as a model Role,
  • Rails enum ,
  • as proposed here ,
  • as a string attribute of the model User.

It all depends on the use case. An example of defining abilities can be found here . In your case, it will look like this:

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
+6
source
+1

, Canard (https://github.com/james2m/canard), CanCanCan RoleModel (https://github.com/martinrehfeld/role_model). .

, , :

class User < ActiveRecord::Base
  acts_as_user roles: [:supervisor, :manager, :writer]
end

, ( ) ( )

Canard::Abilities.for(:user) do
  can  :manage, User, id: user.id
  cannot  [:destroy], User
end

, . - .

0

All Articles