Spree::OrderPopulator.populate ordering two items when one requested

♀尐吖头ヾ 提交于 2019-12-25 02:21:06

问题


I have a program where I am attempting to programatically create Spree orders. I am using the OrderPopulator class to complete this. My code is:

populator = Spree::OrderPopulator.new current_order(create_order_if_necessary: true), current_currency
products.each do |product|
  variant = Spree::Variant.find_by product_id: product.id, is_master: true
  puts "Pre-Items: #{current_order.line_items.count}"
  populator.populate({ products: { product_id: product.id, variant_id: variant.id }, quantity: 1 })
  puts "Post-Items: #{current_order.line_items.count}"
  puts "Products: #{current_order.line_items.first.quantity}"
end

This prints:

Pre-Items: 0
Post-Items: 1
Products: 2

Products should be 1 because that is the quantity I specified when adding the item. What am I doing wrong?


回答1:


You're confusing products and variants a little bit. In Spree 2.1 we have this bit of code:

https://github.com/spree/spree/blob/v2.1.6/core/app/models/spree/order_populator.rb#L21-L27

It allows you to add in a product and/or a variant. Since you've specified two id's in the products hash, it tries to add the first one (product.id) and the second one (variant.id).

I imagine that your quantity is 2 because your product.id == variant.id.

I'd recommend only adding things by variant ID so try:

populator.populate({ variants: { variant_id: variant.id }, quantity: 1 })

Spree 2.2.x has done away with some of this complexity and now populate just takes in a variant id:

https://github.com/spree/spree/blob/v2.2.1/core/app/models/spree/order_populator.rb#L13-L16



来源:https://stackoverflow.com/questions/22723948/spreeorderpopulator-populate-ordering-two-items-when-one-requested

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!