开发者

has_and_belongs_to_many allows no duplicates

I have the following 2 models:

class Order < ActiveRecord::Base
  has_and_belongs_to_many :products, :uniq => false
end

class Product < ActiveRecord开发者_开发知识库::Base
 has_and_belongs_to_many :orders, :uniq => false
end

they are joined by a reference table orders_products

i want order to be able to contain more that 1 instance of same product, so when i @order.product_ids = [2,2,2], which means add 3 times product with id 2

that results in @order.product_ids = [2], is there anyway to tell Model that i do want duplicates?


I would not recommend (neither think of any use) the way you are trying to implement the association here. Although there is a many-many relation between the 2 models, what you are trying to do is drawing 3 lines from point 1 to point 2. If you try to use @order.product_ids = [2,3,4] instead, it should work fine and make sense. In your case, where you want multiple products in an order, you should have some an extra column on the relationship table orders_products that represents the number of Product per Order. In such cases, has_many is recommended over habtm association because you have more control over the relationship table. Read http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜