Ruby on Rails - 如何在不删除整个购物车项目的情况下删除购物车中的单个产品项目



过程摘要

我正在尝试开发一个简单的电子商务应用程序。我创建了变成产品项目的产品,这些产品项目然后添加到购物车,然后添加到订单中。

问题

一切正常 如果我想删除购物车中的所有产品项,请使用以下代码:

      <%= link_to 'Empty Your Cart', @cart, method: :delete, data: {confirm: 'You sure?'} %>

但是我似乎无法弄清楚如何在不删除所有项目的情况下删除一个项目。

我试过使用这个函数

      <%= link_to 'Delete', @product_item, method: :delete, data: {confirm: 'You sure?'} %>

在我的购物车表格上:

<% @cart.product_items.each do|item| %>
       <ul>
        <li>
         <%= item.quantity %>&times;<%= item.product.title %> =
         <%= number_to_currency item.total_price %> - <%=item.product.size %>.
         <%= link_to 'Delete', @product_items, method: :delete, data: {confirm: 'You sure?'} %>
        </li>
       </ul>
  <% end %>

并多次更换我的控制器,但似乎没有任何效果。我确信它可能非常简单,但我是 Rails 的新手,似乎无法弄清楚。

我的购物车控制器

class CartsController < ApplicationController
before_action :set_cart, only: [:show, :create, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
def new
 @cart = Cart.new
end
def show
end

def destroy
 @cart.destroy if @cart.id == session[:cart_id]
 session[:cart_id] = nil
 redirect_to root_url, notice: 'Your cart is empty'
end
private
def set_cart
 @cart = Cart.find(params[:id])
end
def cart_params
 params[:cart]
end
def invalid_cart
 logger_error = 'You are trying to access an invalid cart'
 redirect_to product_url,  notice:'Invalid Cart'
end
end

我的购物车.rb 模型

class Cart < ApplicationRecord
 has_many :product_items, dependent: :destroy
 def add_product(product_id)
  current_item = product_items.find_by(product_id: product_id)
  if current_item
   current_item.quantity += 1
  else
   current_item = product_items.build(product_id: product_id)
  end
   current_item
 end
def total_price
 product_items.to_a.sum{|item| item.total_price}
end
end

我认为您很接近,但您应该将销毁路线更改为特定项目。 因此,@product_items更改为特定项item这是循环中的对象。

<% @cart.product_items.each do|item| %>
   <ul>
    <li>
     <%= item.quantity %>&times;<%= item.product.title %> =
     <%= number_to_currency item.total_price %> - <%=item.product.size %>.
     <%= link_to 'Delete', item, method: :delete, data: {confirm: 'You sure?'} %>
    </li>
   </ul>
<% end %>

最新更新