在 Spree 商店中将多个产品添加到购物车 (Rails 4.2.5.2 / Spree 3.1.0)

Adding multiple products to cart in Spree store (Rails 4.2.5.2 / Spree 3.1.0)

我正在尝试在产品展示页面上创建一个部分,该部分将显示 3 个产品,在它们下方有复选框,以及一个用于将所选产品添加到购物车的按钮。正如我现在所拥有的,只有最后一项被添加到购物车,我相信是因为使用了多个同名变量,并且只选择了最后一个(如讨论的 here)。

上面链接的答案是针对 Spree 2.0.4 的,而我使用的是 3.1.0,所以我不能完全使用那里讨论的答案。

我已经研究了 Spree API,正如 this 问题中所讨论的(并且还使用了 Rails 4 和 Spree 3,非常接近我需要的版本)。但是没有答案,只有评论说 "use the api" 而没有讨论如何做。

另一个 answer 建议使用 Spree Promotions,但我认为这不是我需要的。

(这个 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 %>

所以我最终采用的解决方案是添加一个带有产品 ID 的隐藏字段。然后我将一个 JS 事件处理程序绑定到表单,这样当它被提交时,我会阻止默认操作并创建一个已选中复选框的产品 ID 数组。然后我遍历该数组并向 url /api/v1/orders/${orderNumber}/line_items?line_item[variant_id]=${itemID}&line_item[quantity]=1 的 Spree API 发送 POST 请求,并将它们重定向到购物车页面。