我正在铁轨中建造E商店。我试图从购物车中删除物品,但我不知道我会怎么做。我不确定要开始,因为我是一个总菜鸟,并且一直在遵循一个不包括如何在项目中添加删除功能的教程。
这是指向github repo 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
in 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
答案 0 :(得分:1)
在推车控制器的销毁路径中,您尚未销毁该对象。
所以你要做的就是
的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
视图/推车/ show.html.erb
<td><%= link_to 'remove', remove_cart_path(item.product_id), method: :delete %></td>