设计一个 Rails 应用程序:单表继承? [英] Designing a Rails application: single table inheritance?
问题描述
我已经研究了几天了,我知道有很多文章讨论单表继承和与 Rails 的多态关联.很多有用的材料来自 2009 年或更早,我想知道现在是否有更好的方法来解决这个问题.
I've been researching this for a few days now, and I know there is an abundance of articles that talk about single table inheritance and polymorphic associations with Rails. A lot of helpful material is from 2009 or before and I'm wondering if there is a better approach to this problem now.
该应用程序有几种不同的用户类型(即买方和卖方),每种类型都有一个个人资料.每种用户类型的个人资料确实不同,因此我目前排除了使用一个通用个人资料"表的想法.
The application has a couple of different user types (ie, Buyer and Seller), each of which have a profile. The profile for each user type is really different, so I'm currently ruling out the idea of one generic "profile" table.
这与这个解决方案相同.
class User < ActiveRecord::Base
# authentication stuff
end
class UserType1 < User
has_one :user_type_1_profile
end
class UserType2 < User
has_one :user_type_2_profile
end
...
class UserTypeN < User
has_one :user_type_n_profile
end
根据我的研究,这是一种混合模型"设计.
Based on my research, this is kind of a "mixed model" design.
老实说,在这一点上,我不知道任何其他可行的解决方案.每次我看到类似问题问我看到提出了多态关联的想法.有人可以详细说明多态关联在这种情况下如何工作吗?
Honestly, at this point I don't know of any other solution that would work. Every time I've seen similar questions asked I see the idea of polymorphic associations brought up. Could someone elaborate how a polymorphic association would work in this case?
有人有其他设计建议吗?
Does anyone have any other design suggestions?
推荐答案
在此处使用具有各种配置文件类型的多态关联会更好.
You would be better off with a polymorphic association here with various profile types.
class User < ActiveRecord::Base
belongs_to :profile, :polymorphic => true
end
class ProfileTypeA < ActiveRecord::Base
has_one :user, :as => :profile
end
class ProfileTypeB < ActiveRecord::Base
has_one :user, :as => :profile
end
这需要你有一个这样的迁移/表:
Which would require you have a migration/table like this:
change_table :users do |t|
t.integer :profile_id
t.string :profile_type
# OR (same thing, the above is more explicit)
t.references :profile, :polymorphic => true
end
指南中有更多相关信息:http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
There's more info on this in the Guide: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
这篇关于设计一个 Rails 应用程序:单表继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!