0

I have three models Agreement, Service and Price.

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

But I have two price types in service customer_price and agency_price. Agreement hasn't price type. I want to model something like below. How it is possible?

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

What is best approach? May be I should make two price model like AgreementPrice and ServicePrice. Best Regards.

onurozgurozkan
  • 1,654
  • 1
  • 21
  • 32
  • Why do you think that your approach doesn't work? – alestanis Mar 06 '13 at 12:57
  • Because prices.priceable_type stores only class name (Service or Agreement) not price type (customer_price or agency_price). – onurozgurozkan Mar 06 '13 at 14:10
  • So this means that you want to access customer_price from the Price object and not only from the Service object (in which case your argument is not problematic) – alestanis Mar 06 '13 at 14:27
  • has_many :customer_price, as: :priceable, :conditions => {: priceable_type => 'customer_price'} and has_many : agency_price, as: :priceable, :conditions => {: priceable_type => 'agency_price'} will solve my problem. Question is duplicate with http://stackoverflow.com/questions/2494452/rails-polymorphic-association-with-multiple-associations-on-the-same-model Thanks you for your answer. – onurozgurozkan Mar 06 '13 at 15:53
  • 1
    `has_many :price` is supposed to be `has_many :prices` . 'Plural'. – scaryguy Mar 06 '13 at 18:10

1 Answers1

0

Making two models wouldn't help you actually.

I think you only need to set a specific foreign_key to your relations.

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

Those two fields must be added in your schema.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302