2013-03-06 112 views
0

我有三個模型協議,服務和價格。與多態模型的多has_many關係

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。最好的祝福。

+0

你爲什麼認爲你的方法行不通? – alestanis 2013-03-06 12:57:07

+0

因爲prices.priceable_type僅存儲類名稱(服務或協議)而非價格類型(customer_price或agency_price)。 – onurozgurozkan 2013-03-06 14:10:06

+0

因此,這意味着您想要從Price對象訪問customer_price,而不僅僅是來自Service對象(在這種情況下,您的參數不存在問題) – alestanis 2013-03-06 14:27:14

回答

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 

這兩個字段必須添加到您的模式中。

+0

價格模型是多態的。如果我在價格表中添加foreign_keys,那麼has_many關係有什麼不同? – onurozgurozkan 2013-03-06 19:36:01