ruby - Rails add quantity to cart -


i have question:

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

i want add 1 order item’s quantity before .save called.

the default value of quantity 0. here complete code:

def create     @order_item = @order.order_items.find_or_initialize_by(product_id: params[:product_id])      respond_to |format|       if @order_item.save         format.html { redirect_to @order, notice: 'successfully added product 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 ruby , rails. how 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 |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 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 print out total order_items in order, if example each order_item quantity 2. want print out total quantity.

<%= @order.order_items.count %> 

how that?

if have quantity attribute in order_items table, can assigning value setter, before saving.

@order_item.quantity = 1 

update:
assume, want order items quantities sum. can find total order_items quantities

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

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -