簡體   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