В моей текущей настройке корзины покупок я даю пользователю возможность добавлять предметы в свою корзину в течение его сеанса. Тележка берет идентификатор сеанса и информацию о продукте и создает новую запись @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
Я попробую это, спасибо –
Единственное, что я могу установить, чтобы тележка «устарела», если пользователь ее никогда не удаляет? –
@derek_duncan см. Мой альтернативный метод, который может сработать для вас – David