Search code examples
ruby-on-rails-3has-manybelongs-to

Many model records in has_many-relationship columns


I have a Brand model and a Price model, thus:

brand.rb

class Brand < ActiveRecord::Base
  attr_accessible :name, :a4_single, :a4_double, :a3_double, :two_a3_double
  has_many :prices, :dependent => :destroy
end

price.rb

class Price < Brand
  attr_accessible :type, :quantity, :price, :brand_id
  belongs_to :brand
end

I want to be able to insert multiple Price records into each product column—i.e., say 10 Price records in :a4_single, eight in :a4_double, two in :a3_double, and say eight in :two_a3_double.

I'm only guessing that the has_many relationship defined above is correct, and I really don't know how to proceed from here.


Solution

  • You shouldn't proceed any further.

    Do something like this

    class Brand < ActiveRecord::Base
      has_many :brand_prices
      has_many :prices, :through => :brand_prices
      attr_accessible :name
    end
    
    class Price < ActiveRecord::Base
      has_many :brand_prices
      has_many :brands, :through => :brand_prices
      attr_accessible :price, :quantity, :type
    end
    
    class BrandPrice < ActiveRecord::Base
      belongs_to :brand
      belongs_to :price
    end