【发布时间】: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