我无法弄清楚我的rails line_items控制器创建操作错误?

时间:2014-09-28 14:41:03

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

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

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

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

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

希望这有帮助。