Cancancan default role

613 views Asked by At

I'm building rails app that has some role\abilities separation. I decided to use cancancan + devise, but i can't figure out how to set standard user role?

class User < ActiveRecord::Base
  ROLES = %i[admin moderator author banned]
end
4

There are 4 answers

1
neo On

You can do a callback on your User model:

class User < ActiveRecord::Base
  after_create :assign_default_role

  def assign_default_role
    add_role(:default_role) if self.roles.blank?
  end
end

If after_create isn't suitable, try another callback, more info here

0
Tom H On

When defining abilities, we use an ability called 'user' for default user permissions. In other words, a user with no other roles gets the default set of abilities.

We also use a set of 'guest' permissions for visitors that are not signed in.

0
kimrgrey On

You can use following pattern to simplify Ability class. Notice, that defining rules for "default" role here is very simple, because it's just signed in user without roles.

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    # this is abitilites for anonymous user

    can :read, Post

    return unless user.persisted?

    # ok, now we know that this user is logged in and can define common abilities

    can :create, Post

    # and after it we can define abilities for different roles
    # user.roles here should return name of roles for user, 
    # like [:admin, :moderator]

    user.roles.each { |role| self.public_send(role, user) if respond_to?(role) }
  end

  def admin(user)
    # abitlites for admin here
  end

  def moderator(user)
    # abilities for moderator here
  end
end
0
Dmitry Polyakovsky On

Instead of callback I would set default value on field or in enumeration.

class User
  include Mongoid::Document
  ...
  field :roles,       type: Array # ,  default: [:am]
  extend Enumerize
  enumerize :roles, in: [:superadmin, :am, :salesrep], multiple: true #,  default: :am
end