简体   繁体   中英

Change quantity in Rails shopping cart

I am new to Ruby on Rails. I have built a shopping cart for a sample online store, and I have a shopping cart that I can add items to. If I want to increase the quantity, I have to go back to the product page and add it again. The only way I have to remove a product is to click the Empty Cart button to remove everything.

I am trying to find a way to have the quantity displayed in a number selector of some sort, with the current quantity set as the default value. If the quantity is changed within the cart, then the page will likely need to be refreshed so that the total price can be updated as well. If the quantity is set to 0, then the line item would ideally be removed from the cart.

I am lost when it comes to how to actually implement these features though. Any help would be greatly appreciated.

Here is my /carts/show.html.erb file:

<p id="notice"><%= notice %></p>

<h2>My Cart</h2>
<table class="table table-responsive table-striped">
    <thead>
        <tr>
            <th>Item</th>
            <th>Quantity</th>
            <th>Total Price</th>
        </tr>
        <tbody>
            <%= render(@cart.line_items) %>
            <tr>
                <td>Total</td>
                <td><%= number_to_currency(@cart.total_price) %></td>
                <td></td>
            </tr>
        </tbody>
    </thead>
</table>


<%= button_to 'Empty Cart', @cart, method: :delete, data: {confirm: 'Are you sure you want to empty your cart?'}, :class => 'btn btn-danger' %> 
<br>
<%= button_to "Checkout", new_order_path, method: :get, :class => 'btn btn-success' %>
<br>
<%= link_to 'Back', products_path, :class => 'btn btn-primary' %>

Here is my /line_items/_line_item.html.erb file:

<tr>
    <td><%= link_to line_item.product.product_name, line_item.product %></td>
    <td><%= line_item.quantity %></td>
    <td><%= number_to_currency(line_item.total_price) %></td>
</tr>

There are a number of different ways that this could be accomplished. I guess the easiest way would be to create a method in your cart controller

say...

def update_quantity
  @line_item.update_attribute(:quantity)
end

Then in your view, you can build out a from selector

<%= form_for line_item do |f| %>
  <%= f.select_tag :quantity, 'options_for_quantity' %>
  <%= f.submit, method: :patch %>
<% end %>

That should handle most of what you are looking for.

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