简体   繁体   English

Rails HABTM数量

[英]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. 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 我按照这篇文章进行了设置-> oughbot

But the problem is that I can't access the "q" field when doing this in the console. 但是问题是,在控制台中执行此操作时无法访问“ q”字段。

>> 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. 我将用has_many:through关系替换您的HABTM关系。 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. 当您向联接模型添加其他属性时,在这种情况下,您想添加数量应使用has_many:through而不是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: 编辑:您可以在关于关联的railsguide中阅读更多有关has_many:through和has_and_belongs_to_many之间的区别的信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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