ruby-on-rails - 设计Rails应用程序: single table inheritance?

标签 ruby-on-rails ruby-on-rails-3

我已经对此进行了几天的研究,并且我知道有很多关于单表继承和与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/

相关文章:

ruby-on-rails - HTTP 表单参数字符串可以有多大?

java - 玩!框架与 Ruby on Rails

mysql - 防止 Rails 缓存 ActiveRecord 查询的结果

sql - 复杂 ActiveRecord 案例中大小、长度和计数之间的差异

ruby-on-rails - Ruby、Rails - 如何检查 var 是否是电子邮件

ruby-on-rails-3 - 使用 jquery tokeninput 和 acts_as_taggable_on

javascript - Rails 3.2 Dev 环境 sourceMaps 支持 JavaScript

ruby-on-rails - 如何在本地测试并发?

ruby-on-rails - 如何在 Gitlab CI 上修复 'Rugged::ReferenceError: revspec ' origin/master'not found'

ruby-on-rails - 无法使用带有 Rails 的 axlsx 卡住标题 Pane