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
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
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
You can do a callback on your User model:
If after_create isn't suitable, try another callback, more info here