错误禁止保存该line_item订单必须存在

时间:2018-11-08 06:31:35

标签: ruby-on-rails ruby

我正在尝试通过创建将购物车和产品ID组合在一起的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

0 个答案:

没有答案