简体   繁体   中英

Rails HABTM quantity

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM