【问题标题】:Change quantity in Rails shopping cart更改 Rails 购物车中的数量
【发布时间】:2017-07-05 22:28:24
【问题描述】:

我是 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>

【问题讨论】:

    标签: ruby-on-rails ruby e-commerce shopping-cart


    【解决方案1】:

    有许多不同的方法可以实现这一点。我想最简单的方法是在您的购物车控制器中创建一个方法

    说……

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

    这应该可以处理您正在寻找的大部分内容。

    【讨论】:

      猜你喜欢
      • 2012-04-10
      • 2021-04-19
      • 2020-08-30
      • 1970-01-01
      • 2015-06-01
      • 2010-12-03
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多