从购物车 rails 应用程序中删除商品?

remove item from cart rails app?

我正在 rails 开 E 店。我正在尝试从购物车中移除商品,但我不确定该怎么做。我不确定是否要开始,因为我是个菜鸟,并且一直在学习教程,其中不包括如何向项目添加删除功能。

这是一个 link 到 github 的回购 github.com/DadiHall/brainstore

这里有人可以给我建议吗?

到目前为止我所拥有的是

routes.rb

  resource :cart, only: [:show] do
    post "add", path: "add/:id", on: :member
     delete "remove", path: "destroy/:id", on: :member

    get :checkout
  end

在carts_controller.rb

class CartsController < ApplicationController
    before_filter :initialize_cart

    def add
        @cart.add_item params[:id]
        session["cart"] = @cart.serialize
        product = Product.find params[:id]
        redirect_to :back, notice: "Added #{product.name} to cart."
    end

    def show

    end

    def checkout
        @order_form = OrderForm.new user: User.new
        @client_token = Braintree::ClientToken.generate
    end

    #Delete
    def destroy
     redirect_to cart_path 
   end


end     

在views/cart/show.html.erb

 <% @cart.items.each do |item| %>

    <tr>
    <td><%= item.quantity %></td>
    <td><%= image_tag item.product.image.thumb %><%= link_to item.product.name, item.product %></td>
    <td><%= item.total_price %></td>
      <td><%= link_to 'Empty Cart', cart_path(@cart), method: :delete, confirm: 'are you sure?' %>
</td>
    </tr>
<% end %>

cart.rb 型号

class Cart
    attr_reader :items

    def self.build_from_hash hash
        items = if hash ["cart"] then 
            hash["cart"] ["items"].map do |item_data|
        CartItem.new item_data["product_id"], item_data["quantity"]
        end

    else
        []
    end

        new items
    end


  def initialize items = []
    @items = items
  end

  def add_item product_id
    item = @items.find { |item| item.product_id == product_id }
    if item
      item.increment
    else
      @items << CartItem.new(product_id)
    end
  end

  def empty?
    @items.empty?
  end

  def count
    @items.length
  end

  def serialize 
    items = @items.map do |item| 
        {
            "product_id" => item.product_id, 
            "quantity" => item.quantity
        }
    end

    {

            "items" => items
    }


  end

  def total_price
    @items.inject(0) { |sum, item| sum + item.total_price }
  end




end

cart_item.rb 型号

class CartItem
attr_reader :product_id, :quantity

  def initialize product_id, quantity = 1
    @product_id = product_id
    @quantity = quantity
  end

  def increment
    @quantity = @quantity + 1
  end

  def product
    Product.find product_id
  end

  def total_price
    product.price * quantity
  end


end

在您的购物车控制器的销毁路径中,您还没有销毁对象。

所以你要做的是

routes.rb

delete 'remove', path: 'destroy/:id'

carts_controller.rb

def remove
  cart = session['cart']
  item = cart['items'].find { |item| item['product_id'] == params[:id] }
  if item
    cart['items'].delete item
  end
  redirect_to cart_path
end

views/carts/show.html.erb

<td><%= link_to 'remove', remove_cart_path(item.product_id), method: :delete %></td>