多态模型可以是两种类型

时间:2017-11-22 13:48:11

标签: ruby-on-rails ruby activerecord

我的模型Advertiser可以是branddistributor,也可以是两者。在我的模型中,我有两个布尔属性来找出哪些角色可以拥有Advertiser

重点是Advertiser - distributorhas_many - Advertiser之间存在一些brand关系。

通常我使用多态模型来区分角色,但在这种情况下,我的Advertiser可以同时成为两个角色。

基于实例属性值,我的模型有什么不同的行为吗? 这样的事情可能是:

class Advertiser < ApplicationRecord
  if instance.distributor == true
    has_many :managers
  end
end

1 个答案:

答案 0 :(得分:0)

继续@TomLord,为什么不翻转继承链,即

class Advertiser < ActiveRecord::Base
end

class AdvertiserBoth < Advertiser
  # define any association or behavior that you think both of brand and distributor role should have
end

class Brand < AdvertiserBoth
  # define brand-specific relations and behavior
end

class Distributor < AdvertiserBoth
  # define distributor-specific details
end

在这种方法中,您不必将角色定义为多态,甚至不需要定义任何仅定义角色类型的布尔属性。您还可以避免为问题注释中讨论的目的定义任何共享模块。

如果您认为可以通过这种方式解决案例,您也可以删除AdvertiserBoth类并将所有逻辑放在Advertiser类中。

这种方法的主要优点是您可以在单个数据库表中管理所有这些模型,这就是它被称为Single Table Inheritance (STI)的原因。

相关问题