how to automatically add a role to a user when signing up using devise
I am using Devise 1.1.5. I got a roles
and a roles_assignment
table. Is it possible to assign a role automatically in my role_assignments table when the user signs up? Many thanks!
I tried this but it wont work
class User < ActiveRecord::Base
after_create :assign_role_after_sign_up
protected
def assign_role_after_sign_up(user)
RoleAssignment.create(:role_id => 1, :user_id => user.id)
e开发者_开发技巧nd
end
Your after_create
method won't work because you're trying to pass user
, which isn't much of anything in the model. All user attributes are actually accessible as instance variable, so you should instead do:
def assign_role_after_sign_up
RoleAssignment.create(:role_id => 1, :user_id => id)
end
If you have a relationship between users and role_assignments (and if you don't, why not?), you can simply do this instead:
# If user :has_one :role_assignment
def assign_role_after_sign_up
create_role_assignment(:role_id => 1)
end
# If user :has_many :role_assignments
def assign_role_after_sign_up
role_assignments.create(:role_id => 1)
end
Create an after_create
callback in the User
model that creates and saves a role for the newly created user.
More information about callbacks is available in the Ruby on Rails guides.
精彩评论