0

I'm developing a order system.

Models:
   Orders
   Products
   OrderProducts

Every product have their own quantity field that tells the user how many there are.

I want to be able to order more than one of the same product and mutiple products. ie. HABTM.

class Order < ActiveRecord::Base
    has_and_belongs_to_many :products
end

class Product < ActiveRecord::Base
    has_and_belongs_to_many :categories
    has_and_belongs_to_many :orders
end

class OrdersProducts < ActiveRecord::Base
    belongs_to :product
    belongs_to :order
    validates_presence_of :q
end

I followed this article in setting it up -> thoughbot

But the problem is that I can't access the "q" field when doing this in the console.

>> product = Product.create
>> order = Order.create
>> orders_products = OrdersProducts.create :product => product, :order => order, :q => 10

>> order.products.collect{|each| each.q}
=> NoMethodError: undefined method `q' for #<...

The article I'm referring to is pretty old however.

Philip
  • 6,827
  • 13
  • 75
  • 104

1 Answers1

0

I would replace your HABTM relationship with a has_many :through relationship. When you add additional attributes to your join model, in this case you want to add the quantity you should use has_many :through instead of has_and_belongs_to_many.

Edit: You could read more about the difference between has_many :through and has_and_belongs_to_many in the railsguide about associations:

http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

Peter de Ridder
  • 2,379
  • 19
  • 18
  • The ability to access additional attributes in a HABTM join table was removed in Rails 3.1 in favor of `has_many :through` as described in http://guides.rubyonrails.org/3_1_release_notes.html – Peter Alfvin Sep 15 '13 at 13:31