【问题标题】:Multi has_many relations to polymorphic modelMulti has_many 与多态模型的关系
【发布时间】:2013-03-06 12:54:02
【问题描述】:

我有协议、服务和价格三种模式。

class Agreement < ActiveRecord::Base
  has_many :prices, as: :priceable
end

class Service < ActiveRecord::Base
  has_many :prices, as: :priceable
end

class Price  < ActiveRecord::Base
  attr_accessible :price, :price_currency, :priceable_id, :priceable_type
  belongs_to :priceable, polymorphic: true
end

但我在 service customer_price 和 Agency_price 有两种价格类型。协议没有价格类型。我想建模如下所示的东西。怎么可能?

class Agreement < ActiveRecord::Base
  has_many :prices, as: :priceable
end

class Service < ActiveRecord::Base
  has_many :customer_prices, as: :priceable # I think I should write something here
  has_many :agency_prices, as: :priceable   # I think I should write something here
end

class Price  < ActiveRecord::Base
  attr_accessible :price, :price_currency, :priceable_id, :priceable_type
  belongs_to :priceable, polymorphic: true
end

什么是最好的方法?可能我应该制作两个价格模型,如协议价格和服务价格。最好的问候。

【问题讨论】:

  • 为什么你认为你的方法行不通?
  • 因为 prices.priceable_type 只存储类名称(服务或协议)而不是价格类型(customer_price 或机构_价格)。
  • 所以这意味着您想从 Price 对象访问 customer_price 而不仅仅是从 Service 对象(在这种情况下您的论点没有问题)
  • has_many :customer_price, as: :priceable, :conditions => {: priceable_type => 'customer_price'} 和 has_many : agent_price, as: :priceable, :conditions => {: priceable_type => ' Agency_price'} 将解决我的问题。问题与stackoverflow.com/questions/2494452/… 重复,谢谢您的回答。
  • has_many :price 应该是 has_many :prices 。 '复数'。

标签: ruby-on-rails-3 activerecord polymorphic-associations


【解决方案1】:

制作两个模型实际上对你没有帮助。

我认为你只需要为你的关系设置一个特定的外键。

has_many :customer_price, as: :priceable, :foreign_key => customer_price_id
has_many :agency_price, as: :priceable, :foreign_key => agency_price_id

这两个字段必须添加到您的架构中。

【讨论】:

  • 价格模型是多态的。如果我在价格表中添加foreign_keys,has_many关系有什么不同?
猜你喜欢
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
  • 2012-05-14
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多