在购物车中获取 nil 对象
我正在 Rails 中创建一个简单的购物车,当我将产品添加到购物车时,我收到此错误: 当你没有预料到的时候,你得到了一个 nil 对象!
添加到购物车的方法是:
def add_to_cart
begin
product = Product.find(params[:id])
rescue ActiveRecord::RecordNotFound
logger.error("Attemp to access invalid product #{params[:id]}")
flash[:notice] = "Invalid Product !"
redirect_to :action => :index
else
@cart = find_cart
@cart.add_product(product)
end
end
购物车中的 add_product :
def add_product(product)
current_item = @items.find {|item| item.product == product}
if current_item
current_item.increment_quantity
else
@items << CartItem.new(product)
end
end
购物车工作正常,当我将救援方法添加到 add_to_cart 时,发生了这种情况...
i am creating a simple shopping cart in rails, when I add the product to cart i get this error :
You have a nil object when you didn't expect it!
the add to cart method is :
def add_to_cart
begin
product = Product.find(params[:id])
rescue ActiveRecord::RecordNotFound
logger.error("Attemp to access invalid product #{params[:id]}")
flash[:notice] = "Invalid Product !"
redirect_to :action => :index
else
@cart = find_cart
@cart.add_product(product)
end
end
and the add_product in cart :
def add_product(product)
current_item = @items.find {|item| item.product == product}
if current_item
current_item.increment_quantity
else
@items << CartItem.new(product)
end
end
the cart was working properly, when I add the rescue method to add_to_cart this happened...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许开始会启动一个新的作用域,以便产品变量对其而言是本地的。
然后,当您将产品添加到救援块中时,它是一个带有 Nil 的新本地产品。
要测试这个理论,只需在整个开始之前添加一个
product = nil
,救援代码块Maybe the begin starts a new scope so that the product var is local to it.
And when you then add the product in the rescue block it is a new local with Nil.
To test this theory just add a
product = nil
before the whole begin, rescue block of code我猜测这不是范围问题,正如以下 irb 测试所示:
IMO,解决这个问题的最佳方法是使用
LOGGER.debug 查找后立即找出产品中的内容”产品现在包含#{product.inspect}"
。您的回溯也将提供信息。此时,很难说口译员在抱怨什么。产品可能为零,但也很容易,它可能是@cart 或您认为引用的内容。
I'm going to guess that it's not a scope issue, as the following irb test demonstrates:
The best way to figure this out, IMO, is to find out what's in product immediately after the find using a
LOGGER.debug "product now contains #{product.inspect}"
.Your backtrace will be informational as well. At this point, it's tough to say what the interpreter is complaining about. It could be that product is nil, but just as easily, it could be @cart or something referenced in your view.
add_product 方法中的 @items 是如何定义的?我在任何地方都看不到它,是吗?
How is @items in your add_product method defined? I can't see it anywhere, is it that?