在我当前的购物车设置中,我允许用户在他的会话中将项目添加到他的购物车中。购物车获取会话ID和产品信息并创建一个新的记录@cart.lineitems
。但是,当用户的会话结束时,他们的购物车不会从数据库中删除。这在我的代码中产生了打嗝,并留下一块混乱的石板。我的问题是如何在用户会话结束时删除当前购物车行?会话结束时清除表格轨道
代码:
模式
class Views::CartsController < ApplicationController
layout 'views'
def show
@cart = current_cart
end
end
class Views::Cart < ActiveRecord::Base
# attr_accessible :title, :body
has_many :line_items, :dependent => :destroy
has_one :order, :dependent => :destroy
def total_price
# convert to array so it doesn't try to do sum on database directly
line_items.to_a.sum(&:full_price)
end
end
class Views::LineItem < ActiveRecord::Base
attr_accessible :cart, :quantity, :image, :unit_price, :product_id, :album_id
belongs_to :cart
belongs_to :image
accepts_nested_attributes_for :image
def full_price
unit_price * quantity
end
end
控制器
class Views::LineItemsController < ApplicationController
layout 'views'
def create
@product = Image.find(params[:product_id])
@album = @product.album
attr = {:cart => current_cart, :album_id => @album.id, :product_id => @product.id, :quantity => 1, :unit_price => 10}
@current = Views::LineItem.find_by_product_id(@product.id)
if @current.nil?
Views::LineItem.create(attr)
else
@current.update_attributes(:quantity => @current.quantity + 1, :cart => current_cart)
end
# @line_item = @current ? Views::LineItem.create(:cart => current_cart, :album_id => @album.id, :product_id => @product.id, :quantity => 1, :unit_price => 10) : @current.update_attribute(:quantity, @current.quantity + 1)
flash[:notice] = "Added #{@product.title} to cart."
redirect_to current_cart_url
end
def destroy
@line_item = Views::LineItem.find(params[:id])
if @line_item.quantity > 1
@line_item.update_attribute(:quantity, @line_item.quantity - 1)
else
@line_item.destroy
end
redirect_to current_cart_url
end
end
我会试试,谢谢 – 2013-05-08 23:23:26
唯一的问题是,如果用户永远不会删除它,我该如何将购物车设置为“过期”? – 2013-05-08 23:24:10
@derek_duncan查看我的替代方法,可能适合你 – David 2013-05-08 23:56:53