2017-08-10 88 views
0

我試圖在產品展示頁面上創建一個部分,該部分將顯示3種產品,其下方有複選框,以及一個按鈕將選定的人添加到購物車。就像我現在所做的那樣,只有最後一個項目被添加到購物車中,我相信是因爲使用了多個具有相同名稱的變量,並且只有最後一個被選中(如here所述)。在Spree商店中添加多個產品(Rails 4.2.5.2/Spree 3.1.0)

上面鏈接的答案適用於Spree 2.0.4,我使用的是3.1.0,所以我不能很好地使用那裏討論的答案。

我已經看過Spree API,正如在this問題中討論的那樣(以及使用Rails 4和Spree 3,與我需要的版本非常接近)。但沒有答案,只是一個評論說「使用API​​」,並沒有討論如何這樣做。

另一個answer建議使用Spree促銷,但我不認爲這就是我需要的。

(這other答案使用Rails 3.2,並order_populate他們引用我找不到的型號。)

這裏是我的代碼:

<%= form_for :order, url: populate_orders_path do |f| %> 
    <!-- placeholder; select actual products later --> 
    <% Spree::Product.all.take(3).each_with_index do |product, index| %> 
    <% if product.can_supply? %> 
     <%= render partial: 'spree/products/product', locals: { product: product } %> 
     <%= hidden_field_tag "variant_id", product.master.can_supply? ? product.master.id : product.variants.find(&:can_supply?).id %> 
     <!-- placeholder; replace with checkbox after hardcoded quantity working --> 
     <%= hidden_field_tag :quantity, 1 %> 
     <%#= check_box "quantity", product.master.id, { class: "similar-product-checkbox" } %> 
    <% end %> 
    <% end %> 

    <span class="input-group-btn"> 
    <%= button_tag class: 'btn btn-success primary-cta', id: 'add-pairings-to-cart-button', type: :submit do %> 
    <%= Spree.t(:add_items_to_cart) %> 
    <% end %> 
    </span> 
<% end %> 

回答

1

所以我結束了去解決正在添加一個帶有產品ID的隱藏字段。然後,我將一個JS事件處理程序綁定到表單,所以當它被提交時,我會阻止默認操作並創建一個選中複選框的產品ID數組。然後,我遍歷該數組並向POST Spree API發送POST請求,地址爲/api/v1/orders/${orderNumber}/line_items?line_item[variant_id]=${itemID}&line_item[quantity]=1,並將它們重定向到購物車頁面。

相關問題