简体   繁体   中英

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.

The default value of the quantity is 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

<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 . 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_item.quantity = 1


I assume, you want order items quantities sum. You can find total order_items quantities by

@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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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