如何在 rails 的购物车中添加多个项目?

How to add several items in shopping cart in rails?

我在 rails 的简单商店中遇到了一些问题。我想在购物车中添加一组已选择的产品,但我不知道如何。

我在我的 3 组产品上使用单选按钮,我希望用户选择所有 3 个项目,然后按下按钮 "add to cart"。

在购物车中,它必须是这样的数组:username-mix(1-id, 2-id, 3-id)。但我还有一个问题。我无法获取我的产品 ID,也不知道为什么。

产品全部来自 seed.db,字段为::category_id, :menu_id, :title, :price, :discribe and :path_to_image

这是我的代码:

 class ProductController < ApplicationController
   before_action :admin_user, only: :edit

   def show
     @products = Product.where("category_id = 1").limit(3)
     @products2 = Product.where("category_id = 2").limit(3)
     @products3 = Product.where("category_id = 3").limit(3)
   end

   private

   def product_params
     params.permit(
       :category_id,
       :menu_id,
       :title,
       :discribe,
       :price,
       :path_to_image
     )
   end
 end

我的Product模特:

class Product < ApplicationRecord
  validates :title, presence: true
  validates :price, presence: true
  belongs_to :category
end

product/show/html.erb

<div class="col-md-4 about-left">
  <table class="tfood">
    <td><p><b>Main</b></p></td>
    <% @products.each do |i| %>
      <tr>
        <td>
          <%= i.title %><%= image_tag i.path_to_image %>
        </td>
        <td>
          <%= i.discribe %>
          <p><b>Price: <%= i.price %></b></p>
          <input name="main" type="radio" value="">
        </td>
      </tr>
    <% end %>
  </table>
</div>
<div class="col-md-4 about-left">
  <table class="tfood">
    <td>
      <p><b>Topping</b></p>
    </td>
    <% @products2.each do |i| %>
      <tr>
        <td>
          <%= i.title %>
          <%= image_tag i.path_to_image %>
        </td>
        <td>
          <%= i.discribe %>
          <p><b>Price: <%= i.price %></b></p>
          <input name="topping" type="radio" value="">
        </td>
      </tr>
    <% end %>
  </table>
</div>
<div class="col-md-4 about-left">
  <table class="tfood">
    <td>
      <p><b>Drink</b></p>
    </td>
    <% @products3.each do |i| %>
      <tr>
        <td>
          <%= i.title %>
          <%= image_tag i.path_to_image %>
        </td>
        <td>
          <%= i.discribe %>
          <p><b>Price: <%= i.price %></b></p>
          <input name="drink" type="radio" value="">
        </td>
      </tr>
    <% end %>
  </table>
</div>
<script>
  function add_to_cart(id){
    var x = window.localStorage.getItem(id);
    x = x * 1 + 1;
    window.localStorage.setItem(id, x);
  }
</script>

您似乎没有在单选按钮中设置值。也许写一些像

这样的东西会更好
<input name="drink" type="radio" value=<%= i.id %>>

注意。我没有在 IDE 中检查我的代码,这只是想法。实际上我大约一年前在 ERB 工作过,但我不确定语法。