使用devise进行注册时如何自动向用户添加角色 [英] how to automatically add a role to a user when signing up using devise
问题描述
我正在使用Devise 1.1.5.我有一个 roles
和一个 roles_assignment
表.用户注册后,是否可以在我的role_assignments表中自动分配角色?非常感谢!
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!
我试过了,但是没用
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)
end
end
推荐答案
您的 after_create
方法无法正常工作,因为您正试图传递 user
,而这是'模型中的很多东西.实际上,所有用户属性都可以作为实例变量进行访问,因此您应该执行以下操作:
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
如果您在用户和role_assignments之间有关系(如果没有,为什么不这样做?),您可以简单地执行以下操作:
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
这篇关于使用devise进行注册时如何自动向用户添加角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!