繁体   English   中英

Rails添加数量到购物车

[英]Rails add quantity to cart

我有个问题:

@order_item = @order.order_items.find_or_initialize_by(product_id: params[:product_id])

我想在调用.save之前向订单商品的数量添加一个。

quantity的默认值为0 这是我完整的代码:

def create
    @order_item = @order.order_items.find_or_initialize_by(product_id: params[:product_id])

    respond_to do |format|
      if @order_item.save
        format.html { redirect_to @order, notice: 'Successfully added product to cart.' }
        format.json { render :show, status: :created, location: @order_item }
      else
        format.html { render :new }
        format.json { render json: @order_item.errors, status: :unprocessable_entity }
      end
    end
  end

我是红宝石和铁轨的新手。 怎么做? 谢谢

UPDATE

<tr>
    <th>Items:</th>
    <td><%= @order.order_items.count %></td>
  </tr>
  <tr>
    <th>Items</th>
    <th>Title</th>
    <th>Quantity</th>
    <th>Unit Price</th>
    <th>Subtotal</th>
    <th></th>
  </tr>
  <% @order.order_items.each do |item| %>
    <tr>
        <td><%= image_tag "products/#{item.product.image_url}" %></td>
        <td><%= item.product.title %></td>
        <td><%= item.quantity %></td>
        <td><%= print_price item.product.price %></td>
        <td><%= print_price item.subtotal %></td>
    <td><%= link_to 'Remove', item, method: :delete, data: { confirm: 'Are you sure?' } %></td>
    </tr>
  <% end %>
  <tr>
    <th>TOTAL</th>
    <td></td>
    <td></td>
    <td></td>
    <td><%= print_price @order.total %></td>
    <td></td>
  </tr>

我当前的代码仅按某种order打印出总order_items ,例如,如果每个order_item数量为2 ,该怎么办。 所以我想打印出所有的总数。

<%= @order.order_items.count %>

怎么做?

如果在order_items表中具有数量属性,则可以在保存之前,只需将值分配给设置器即可。

@order_item.quantity = 1

更新:
我假设,您要订购商品的数量总和。 您可以按以下顺序查找order_items的总数量

@order.order_items.sum(:quantity) 

更换您的

<th>Items:</th>
<td><%= @order.order_items.count %></td>

<th>Items:</th>
<td><%= @order.order_items.sum(:quantity) %></td>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM