简体   繁体   English

更改Rails购物车中的数量

[英]Change quantity in Rails shopping cart

I am new to Ruby on Rails. 我是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. 如果数量设置为0,则理想情况下将订单项从购物车中删除。

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: 这是我的/carts/show.html.erb文件:

<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: 这是我的/line_items/_line_item.html.erb文件:

<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 然后在您的视图中,您可以构建一个from选择器

<%= 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. 那应该可以满足您的大部分需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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