【问题标题】:Designing a Rails application: single table inheritance?设计 Rails 应用程序:单表继承?
【发布时间】:2011-10-10 22:54:45
【问题描述】:

这几天我一直在研究这个问题,我知道有很多文章都在讨论单表继承和 Rails 的多态关联。很多有用的材料来自 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 问我都会看到多态关联的想法。有人可以详细说明在这种情况下多态关联是如何工作的吗?

还有其他设计建议吗?

【问题讨论】:

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


    【解决方案1】:

    在此处使用与各种配置文件类型的多态关联会更好。

    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

    【讨论】:

    • 这对我来说很有意义。你介意指出这种设计相对于我原来的方法的好处吗?我相信这种方法是有益的,但如果我能理解为什么会很好。
    • 这准确地模拟了您所代表的数据,至少据我所知。当您有许多共享通用功能的不同对象时,STI 更适合。你没有那个。您的用户都有不同行为的个人资料。
    • 我现在明白这一点,这很有意义。谢谢!
    • 有没有办法在用户模型上使用accepts_nested_attributes_for :profile,还是我需要在每个单独的配置文件模型上使用它?
    • 注意迁移示例中的错字:(正确)change_table :users do |t| t.references :profile, :polymorphic => true end
    猜你喜欢
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 2017-01-25
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    相关资源
    最近更新 更多