Rails 3: Add roles to a user
I'm using cancan as my authorization engine.
I already have the roles in user:
ROLES = %w[admin normal author corp]
I also have methods to add and check roles:
#cancan
def roles=(roles)
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
end
def roles
ROLES.reject do |r|
((roles_mask || 0) & 2**ROLES.index(r)).zero?
end
end
def is?(role)
roles.include?(role.to_s)
end
And I have # roles_mask :integer
in the User model.
However, I want to开发者_StackOverflow社区 have a after_save :add_normal_role
which assigns the normal role to the user.
Basically, I'm not being able (don't know) how to assign roles to each user.
This is what I have, which doesn't work:
private
def add_normal_role
self.roles=(ROLES[1])
end
Thanks
You should try using a before_create callback ensuring the user has a normal role.
The problem with your current callback is since it's an after_save, your modifications aren't saved by default. (Saving in an after_save callback is a bad idea leading to infinite loops...) You could also use a before_save callback (with the same code you already have), which will also work.
However, since you really only need to add a normal role when the object is created (and not on every update), a before_create is better suited.
精彩评论