[英]Rails devise gem and user groups
我正在使用rails devise gem進行用戶身份驗證,但現在我的商店必須介紹用戶組,以獲取discont,特價等。如何使用devise進行此操作? 請注意,這是一個/多對多,因為每個用戶可以擁有多個組,每個組都有一些用戶。
此外,當用戶注冊時,組必須是例如1。
Devise已經“關閉”了控制器(不像authlogic那樣)。 那也是麻煩。
def create
super
group = Group.find_by_name("newuser")
user_group = UserGroup.create
user_group.user_id = current_user.id
user_group.group_id = group.group_id
user_group.save
end
除非我錯誤地閱讀您的問題,否則不一定必須與Devise集成。 只需創建一個描述組屬性的Group模型,以及UserGroup連接模型:
class UserGroup < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
class User < ActiveRecord::Base
has_many :user_groups
has_many :groups, :through => :user_groups
# attr_accessible :user_id, :group_id
end
class Group < ActiveRecord::Base
has_many :user_groups
has_many :users, :through => :user_groups
end
至於關閉的控制器問題,您可以將Devise控制器提升到您的應用程序中,或者創建一個繼承它的新控制器,從而覆蓋這些方法。 閱讀他們的鏈接GitHub頁面 。
編輯:我認為你是從錯誤的角度接近這個。 你不需要在Devise的控制器中做任何事情,而是在你的User模型中添加一個before_save
回調。
class User < ActiveRecord::Base
before_save(:on => :create) :assign_default_group
# Other model stuff here
private
def assign_default_group
# This automatically creates the UserGroup record
self.groups << Group.find_by_name("User")
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.