[英]undefined method `+' for nil:NilClass
I want to complete a cart part in a site. 我想在网站上填写购物车零件。 The first time i add items into the cart it is ok, but the second time with the same items i would get a error: 第一次将商品添加到购物车中就可以了,但是第二次使用相同的商品会出现错误:
undefined method `+' for nil:NilClass
Extracted source (around line #19):
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity += 1
else
current_item = line_items.build(product_id: product_id)
end
What is wrong? 怎么了?
Thanks. 谢谢。
The quantity field is probably null in the database. 数量字段在数据库中可能为空。 Change the infringing line to something like: 将侵权行更改为以下内容:
current_item.quantity = current_item.quantity.to_i + 1
nil.to_i
returns 0
nil.to_i
返回0
So use current_item.quantity = current_item.quantity.to_i + 1
因此,使用current_item.quantity = current_item.quantity.to_i + 1
Seems like current_item.quantity
is nil
. 似乎current_item.quantity
为nil
。
Try to set default value with 尝试使用设置默认值
...
if current_item
current_item.quantity ||= 1 # sets to 1 if nil
current_item.quantity += 1
else
...
If you store quantity
in database, then add to your migration like null: false, default: 1
如果将quantity
存储在数据库中,则将其添加到您的迁移中,如null: false, default: 1
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.