2014-03-28 14 views
0

我有一個程序,我試圖以編程方式創建施普雷訂單。我正在使用OrderPopulator類完成此操作。我的代碼是:Spree :: OrderPopulator.populate訂購兩個項目時,請求

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,因爲這是加入該項目的時候我所指定的數量。我究竟做錯了什麼?

回答

2

您正混淆產品和變體的一點點。在施普雷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 }) 

施普雷2.2.x中已經有一些這方面的複雜的廢除,現在填充只需要在一變ID:

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

+0

類似的問題,這 http://stackoverflow.com/questions/24759046/spreeorderpopulator-accessing-outside-店外 –