与多态模型的多重关系

时间:2013-03-06 12:54:03

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

我有三种型号协议,服务和价格。

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

但我在服务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

什么是最好的方法?也许我应该制作像AgreementPrice和ServicePrice这样的两个价格模型。最诚挚的问候。

1 个答案:

答案 0 :(得分:0)

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

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

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

必须在架构中添加这两个字段。