Spree :: OrderPopulator.populate在请求时订购两个项目

时间:2014-03-28 22:01:53

标签: ruby-on-rails spree

我有一个程序,我试图以编程方式创建Spree订单。我正在使用OrderPopulator类来完成此操作。我的代码是:

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

打印:

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

Products应为1,因为这是我在添加项目时指定的数量。我做错了什么?

1 个答案:

答案 0 :(得分:2)

您稍微混淆了产品和变体。在Spree 2.1中,我们有一些代码:

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

它允许您添加产品和/或变体。由于您在产品哈希中指定了两个ID,因此它会尝试添加第一个(product.id)和第二个(variant.id)。

我想你的数量是2,因为你的product.id == variant.id。

我建议只根据变体ID添加内容,所以请尝试:

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

Spree 2.2.x已经废除了一些复杂性,现在填充只需要一个变体id:

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