我已经对此进行了几天的研究,并且我知道有很多关于单表继承和与Rails的多态关联的文章。很多有用的 Material 来自2009年或更早之前,我想知道现在是否有更好的方法来解决此问题。
情况
该应用程序具有几个不同的用户类型(即买方和卖方),每个用户类型都有一个配置文件。每种用户类型的配置文件实际上是不同的,因此我目前正在排除一个通用的“配置文件”表的概念。
我目前的做法
与this解决方案相同。
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
根据我的研究,这是一种“混合模型”设计。
老实说,目前我还不知道其他可行的解决方案。每次我看到similar questions时,我都会看到多态关联的想法。有人可以详细说明这种情况下的多态关联如何工作吗?
有人还有其他设计建议吗?
最佳答案
您最好在这里使用具有多种配置文件类型的多态关联。
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
这将需要您有一个这样的迁移/表:
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
关于ruby-on-rails - 设计Rails应用程序: single table inheritance?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7719600/