【问题标题】:I can't figure out my rails line_items controller create action error?我无法弄清楚我的 rails line_items 控制器创建操作错误?
【发布时间】:2023-03-06 04:22:01
【问题描述】:

尝试将产品添加到购物车时出现此错误:

ActiveRecord::RecordNotFound in LineItemsController#create
Couldn't find Cart with 'id'=2

所以创建操作有问题,但我不确定它是什么... 创建操作:(@product 和数量之间的差距在我的实际代码中不存在,无法格式化对。)

def create
  @product = Product.find(params[:product_id])
  @line_item = LineItem.create!(:cart => current_cart, :product => @product, 

  :quantity=>    1, :unit_price => @product.price)
  flash[:notice] = "Added #{@product.name} to cart."
  redirect_to cart_url(current_cart)

结束

来自应用程序控制器的 current_cart 方法:

def current_cart
session[:cart_id] ||= Cart.create!.id
@current_cart ||= Cart.find(session[:cart_id])
end

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 error-handling


    【解决方案1】:

    您的代码在 ApplicationController#current_cart 方法中失败。会话中是否已有购物车 ID?如果是这样,代码将尝试查找具有该 ID 的购物车记录,如果它已被删除,它将失败并显示上述消息。

    所以,首先,弄清楚你在会话中拥有什么。其次,弄清楚如何在不提供应用程序陈旧或无效数据的情况下创建新购物车。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 2020-11-14
      相关资源
      最近更新 更多