簡體   English   中英

更改Rails購物車中的數量

[英]Change quantity in Rails shopping cart

我是Ruby on Rails的新手。 我已經為示例在線商店構建了一個購物車,並且我有一個可以添加商品的購物車。 如果要增加數量,則必須返回到產品頁面並再次添加。 我必須刪除產品的唯一方法是單擊“清空購物車”按鈕刪除所有內容。

我試圖找到一種方法,以某種數量的數字選擇器顯示數量,並將當前數量設置為默認值。 如果購物車內的數量發生變化,則可能需要刷新頁面,以便總價格也可以更新。 如果數量設置為0,則理想情況下將訂單項從購物車中刪除。

不過,我對於如何真正實現這些功能感到迷茫。 任何幫助將不勝感激。

這是我的/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' %>

這是我的/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>

有許多不同的方法可以實現這一點。 我猜最簡單的方法是在購物車控制器中創建一個方法

說...

def update_quantity
  @line_item.update_attribute(:quantity)
end

然后在您的視圖中,您可以構建一個from選擇器

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

那應該可以滿足您的大部分需求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM