Devise中的两种截然不同的用户模型 [英] Two very different user models in Devise
问题描述
我的应用程序中有两种不同类型的用户,它们使用Devise通过Rails 4进行身份验证,但是它们具有非常不同的字段.一个是买方,另一个是卖方.买方必须拥有位置和付款信息,而卖方则没有.最初,我认为创建两个单独的Devise模型是一个好主意,但必须有一种更好的方法.我考虑过将它们放在同一张表中,然后序列化买方的付款数据.
I have two different types of users in my application that uses Devise for authentication using Rails 4 but they have very different fields. One is a Buyer and the other is a Seller. The Buyer must have location and payment information while the Seller doesn't. Initially I thought it would be a good idea to create two separate Devise models but there has to be a better way. I thought about keeping it all in the same table and serializing the Buyer's payment data.
什么是好的解决方案?
推荐答案
看看STI-简而言之,您创建一个称为User
的基本模型,然后创建两个子类User::Buyer
和User::Seller
(无需命名空间) ,但建议).两种模型都存储在同一表中,应用于User
模型的所有内容都将影响这两个类.有关STI的更多信息此处
Have a look at STI - in short you create one base model called User
and then two subclasses User::Buyer
and User::Seller
(No need for namespacing, but it is recommended). Both models are stored in same table and everything applied to User
model will affect both those classes. More about STI here
更新:
如果您不希望有许多空表单元格,则可以使用1-1关联来保留所有特定于类的详细信息.您还可以添加包装器以将其完全封装.看起来可能像这样:
If you don't want to have a number of empty table cells, you might use 1-1 association to keep all class-specific details. You can also add a wrapper to encapsulate it completely. It could look like this:
class User < ActiveRecord::Base
belongs_to :details, polymorphic: true
def method_missing(method, *args)
return details.send(method, *args) if details.respond_to? method
super
end
end
class BuyerDetails < ActiveRecord::Base
has_one :user, as: :details
# buyer_attribute column
end
class SellerDetails < ActiveRecord::Base
has_one :user, as: details
#seller_attribute
end
然后可以将其与STI混合:
You can then mix it with STI:
class User::Buyer < User
def initialize(*args)
super
details = BuyerDetails.new
end
end
class User::Seller < User
def initialize(*args)
super
details = SelerDetails.new
end
end
然后,您可以使用以下方法简化工作:
Then you can simple work using:
user = User::Buyer.new
user.buyer_attribute #=> nil
user.seller_attribute #=> NoMethod error!
注意:您将需要在User
模型以及details_id
上具有details_type
字符串列,以使多态关联起作用.对于STI,您将需要另一列type
.
Note: You will need to have details_type
string column on your User
model as well as details_id
for polymorphic association to work. For STI, you will need another column type
.
这篇关于Devise中的两种截然不同的用户模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!