【问题标题】:Rails Shopping Cart Not Adding and/or Showing the Right ProductsRails 购物车未添加和/或显示正确的产品
【发布时间】:2017-02-14 10:29:57
【问题描述】:

我正在通过 youtube 教程构建一个非常基本的购物车。我遇到的问题是,虽然添加产品的链接存在并重定向到购物车而不引发异常,但它总是添加并显示列表中的第一个产品(如果我销毁第一个产品,那么下一个一个出现)。

我知道问题在于 add 方法,它没有按应有的方式存储多个产品 ID。

cart_controller.rb

class CartController < ApplicationController

def add
id = params[:id]
if session[:cart] then
  cart = session[:cart]
else
  session[:cart] = {}
  cart = session[:cart]
end

if  cart[:id] then
    cart[:id] = cart[:id] + 1
else
    cart[:id] = 1
end
redirect_to cart_url

end

def clearCart
session[:cart] = nil
redirect_to cart_url
end


def index
  if session[:cart] then
    @cart = session[:cart]
  else
    @cart = {}
  end
end

end

购物车索引.html

<%= link_to 'Empty Your Cart', cart_clear_path %>


 <% @cart.each do | id, quantity| %>
  <% product = Product.find_by(id) %>
  <ul>
    <li><%= link_to product.title, product %></li>

  </ul>

<% end %>

产品索引.html

`<% @products.each do |product| %>`
    <tr>  
    <td><%= product.title %></td>
    <td><%= product.description %></td>
    <td><%= product.image_url %></td>
    <td><%= product.price %></td>
            <td><%= product.category %></td>
                    <td><%= product.subcategory %></td>
    <td><%= link_to 'Show', product %></td>
    <td><%= link_to 'Edit', edit_product_path(product) %></td>
    <td><%= link_to 'Destroy', product, method: :delete, data: { confirm:      'Are you sure?' } %></td>
    <td><a href="/cart/<%= product.id %>">Add to Cart</a></td>
  </tr>
<% end %>

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    自己找到了解决方案。事实上,add 方法解决了这个问题。 :id 参数已经存储在 id 变量中。

    if  cart[id] then
      cart[id] = cart[id] + 1
    else
      cart[id] = 1
    

    还修改了产品变量。

    product = Product.find_by(id: id)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2018-12-04
      相关资源
      最近更新 更多