我在電子商務應用程序中遇到了我的購物車問題。 當用戶登錄並將商品添加到購物車時,該商品不會立即添加。 用戶在進入購物車之前必須重新添加。Rails Cart刪除自身
我已經看過日誌,並且我已經能夠發現問題發生在用戶先前購買了某件東西並且正在簽署購買日後。下次他們登錄購買另一件物品,是什麼時候發生的。
系統嘗試刪除舊購物車並創建一個新購物車,但最終發生的是,新購物車在第一次嘗試時顯示爲空。
有沒有辦法避免這種情況?
任何幫助,將不勝感激。提前致謝!
class Customer::CartsController < ApplicationController
before_action :authenticate_user!
def show
if current_user
if current_user.cart.purchased_at
session[:cart_id] = nil
else
@cart = current_user.cart ||= Cart.find_by(session[:cart_id])
end
end
if session[:cart_id].nil?
current_user.cart = Cart.create!(user_id: params[:id])
session[:cart_id] = current_user.cart.id
end
@cart = current_user.cart
end
的車控制器創建行動
class CartsController < ApplicationController
def create
@cart = Cart.new(cart_params)
respond_to do |format|
if @cart.save
format.html { redirect_to @cart, notice: 'Cart was successfully created.' }
format.json { render :show, status: :created, location: @cart }
else
format.html { render :new }
format.json { render json: @cart.errors, status: :unprocessable_entity }
end
end
end
車型號
class Cart < ActiveRecord::Base
has_many :line_items, dependent: :destroy
belongs_to :user
def add_product(product_id, size)
current_item = line_items.find_by(product_id: product_id, size: size)
if current_item
current_item.quantity += 1
else
current_item = line_items.build(product_id: product_id, size: size)
end
return current_item
end
def total_price
line_items.to_a.sum { |item| item.total_price }
end
end
用戶模型
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :invitable,
has_one :cart
after_create :default_cart
def add_products_from_session cart_id
if role == customer?
session_cart = Cart.find cart_id if cart_id
end
if cart && session_cart
session_cart.line_items.each{ |li| self.cart.line_items << li }
session_cart.reload
session_cart.destroy
elsif session_cart
self.cart = session_cart
end
private
def default_cart
self.create_cart
end
end
代碼,增加了產品的購物車
從行項目控制器
def create
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id, params[:size])
respond_to do |format|
if @line_item.save
format.html { redirect_to customer_cart_path }
format.json { render :show, status: :created, location: @line_item }
else
format.html { render :new }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end
請問您還可以添加您的購物車和用戶模型嗎? –
@GrahamS。添加 –
什麼是控制器#產生意想不到的行爲?你有沒有爲它寫過測試? – eeeeeean