Ошибка запретила сохранение этого line_item Заказ должен существовать - PullRequest
0 голосов
/ 08 ноября 2018

Я пытаюсь найти решение для добавления товара в корзину, создав компонент line_item, который объединит идентификаторы корзины и продукта. Когда я добавляю товар в корзину, я перенаправляю себя на /line_items?product_id=1, и у меня постоянно появляется ошибка: Error prohibited this line_item from being saved. Order must exist

Я чувствую, что проблема заключается в этом создать контроллер line_item

product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)

# @cart.save!

if @line_item.save
  render json: { cart_url: cart_path(@cart), card_id: @cart.id }
else
  render :new
end

Моя корзина Модель

  def add_product(product_id)
    current_item = line_items.find_by(product_id: product_id)
    if current_item
      current_item.increment(:quantity, 1)
    else
      current_item = line_items.build(product_id: product_id)
    end
    current_item
  end

И я увидел, что терминал пытается откатить что-то в текущей корзине

Started POST "/line_items?product_id=1" for 127.0.0.1 at 2018-11-08 00:24:54 -0600
Processing by LineItemsController#create as HTML
  Parameters: {"authenticity_token"=>"Y6t2ZiEeWLDoV8jrL27ak0X8TXCAw==", "product_id"=>"1"}
   (0.2ms)  BEGIN
  ↳ app/controllers/concerns/current_cart.rb:10
   (0.3ms)  ROLLBACK
  ↳ app/controllers/concerns/current_cart.rb:10
  User Load (3.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/line_items_controller.rb:15
  Product Load (1.1ms)  SELECT  "products".* FROM "products" WHERE "products"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/line_items_controller.rb:22
   (0.3ms)  BEGIN
  ↳ app/controllers/line_items_controller.rb:27
  Product Load (1.4ms)  SELECT  "products".* FROM "products" WHERE "products"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/line_items_controller.rb:27
   (0.4ms)  ROLLBACK
  ↳ app/controllers/line_items_controller.rb:27
  Rendering line_items/new.html.erb within layouts/application
  Rendered line_items/_form.html.erb (3.5ms)
  Rendered line_items/new.html.erb within layouts/application (6.7ms)

И моя текущая корзина

module CurrentCart
  extend ActiveSupport::Concern

  private

  def set_cart
    begin
      @cart = Cart.find(params[:card_id] || session[:cart_id])
    rescue ActiveRecord::RecordNotFound
      @cart = Cart.create
    end

    session[:card_id] = @cart.id
  end
end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...