Reputation:
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
Upvotes: 1
Views: 627
Reputation: 1585
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
Upvotes: 0
Reputation: 562
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
Upvotes: 0
Reputation: 207
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.
Upvotes: 0