Devise中两个非常不同的用户模型

我的应用程序中有两种不同类型的用户使用Devise进行身份validation使用Rails 4,但它们具有非常不同的字段。 一个是买方,另一个是卖方。 买方必须拥有位置和付款信息,而卖方则不需要。 最初我认为创建两个单独的Devise模型是一个好主意,但必须有更好的方法。 我考虑将所有内容保存在同一个表格中并序列化买方的付款数据。

什么是好的解决方案?

看看STI – 简而言之,你创建了一个名为User基本模型,然后是两个子类User::BuyerUser::Seller (不需要命名空间,但建议使用)。 两个模型都存储在同一个表中,应用于User模型的所有内容都会影响这两个类。 更多关于STI的信息

更新:

如果您不想拥有多个空表格单元格,则可以使用1-1关联来保留所有特定于类的详细信息。 您还可以添加包装器以完全封装它。 它可能看起来像这样:

 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混合:

 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 

然后你可以使用简单的工作:

 user = User::Buyer.new user.buyer_attribute #=> nil user.seller_attribute #=> NoMethod error! 

注意:您需要在User模型上具有details_type字符串列以及details_id多态关联工作的details_id 。 对于STI,您将需要其他列type

老实说,我使用多态关系。 我保持我的用户模型非常适合身份validation,然后使两个新模型(买方和卖方)使用他们不共享的字段。 这与上面显示的BroiSate方法非常接近。

 class User < ActiveRecord::Base belongs_to :authenticatable, polymorphic: true end class Buyer < ActiveRecord::Base has_one :user, as: :authenticatable # Add buyer specific fields to this table end class Seller < ActiveRecord::Base has_one :user, as: :authenticatable # Add seller specific fields to this table end