У меня есть корзина Rails для клиента, который работает, но только на второй попытке попробовать «добавить в корзину».Проблема с Rails с корзиной пользователя
Поэтому каждый раз, когда я нажимаю «добавить в корзину», тележка пуста в первый раз. Но при второй попытке элемент добавляется в корзину.
Что я делаю неправильно?
Вот код контроллера клиента:
class Customer::CartsController < ApplicationController
before_action :authenticate_user!
def show
@cart = if current_user
current_user.cart ||= Cart.find_by(session[:cart_id])
session[:cart_id] = nil if current_user.cart.purchased_at
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
end
Обычный контроллер Тележки
class CartsController < ApplicationController
skip_before_action :authorize, only: [:create, :update, :destroy]
before_action :set_cart, only: [:show, :edit, :update, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
def index
@carts = Cart.all
end
def show
end
def new
@cart = Cart.new
end
def edit
end
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
def update
respond_to do |format|
if @cart.update(cart_params)
format.html { redirect_to @cart, notice: 'Cart was successfully updated.' }
format.json { render :show, status: :ok, location: @cart }
else
format.html { render :edit }
format.json { render json: @cart.errors, status: :unprocessable_entity }
end
end
end
def destroy
@cart.destroy if @cart.id == session[:cart_id]
session[:cart_id] = nil
end
respond_to do |format|
format.html { redirect_to root_path, notice: 'Your Cart is currently empty.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cart
@cart = Cart.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def cart_params
params[:cart]
end
def invalid_cart
logger.error "Attempt to access invalid cart #{params[:id]}"
redirect_to root_path, notice: 'Invalid cart'
end
end
контроллер Line Items создать метод
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
Любая помощь будет оценена. Заранее спасибо!
Спасибо за ваш ответ, но у меня нет метода 'current_cart' в приложении. контроллер. Я создал контроллер Customer, который наследуется от контроллера Carts (выше), вместо использования метода текущей корзины. Пробовал вызов '@cart = current_user.cart' метода в контроллере LineItems до' cart.add_product', но он тоже не работал. –
Посмотрите на редактирование там –
Я сделал это немного по-другому, я создаю корзину каждый раз, когда пользователь создан. Поэтому в моей модели пользователя у меня есть этот обратный вызов> 'after_create: default_cart' ' def default_cart self.create_cart 10 end' –