[英]Rails add quantity to cart
I have a question: 我有个问题:
@order_item = @order.order_items.find_or_initialize_by(product_id: params[:product_id])
I want to add one to the order item's quantity before the .save
is called. 我想在调用
.save
之前向订单商品的数量添加一个。
The default value of the quantity
is 0
. quantity
的默认值为0
。 Here is my complete code: 这是我完整的代码:
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
Im new to ruby and rails. 我是红宝石和铁轨的新手。 How to do that?
怎么做? Thank you
谢谢
UPDATE 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>
My current code is only print out total order_items
in some order
, what if for example each order_item
quantity is 2
. 我当前的代码仅按某种
order
打印出总order_items
,例如,如果每个order_item
数量为2
,该怎么办。 So I want to print out all total quantity. 所以我想打印出所有的总数。
<%= @order.order_items.count %>
How to do that? 怎么做?
If you have quantity attribute in order_items table, you can do that by simply assigning value to the setter, before saving. 如果在order_items表中具有数量属性,则可以在保存之前,只需将值分配给设置器即可。
@order_item.quantity = 1
Update:
更新:
I assume, you want order items quantities sum. 我假设,您要订购商品的数量总和。 You can find total order_items quantities by
您可以按以下顺序查找order_items的总数量
@order.order_items.sum(:quantity)
Replace your 更换您的
<th>Items:</th>
<td><%= @order.order_items.count %></td>
with 同
<th>Items:</th>
<td><%= @order.order_items.sum(:quantity) %></td>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.