[英]Rails Error: undefined method ` ' for nil:NilClass
因此,由于我对Rails(和ruby)还很陌生,所以我仍在尝试了解所有错误在哪里 。 我正在网上商店的购物车上工作。 用户将获得一个会话,其中将存储他的购物车商品(在这种情况下为line_item.rb)。
问题:当我单击一个项目时,它通过购物车方法add_product被添加到购物车中。 如果您再次单击同一项目,而不是将同一项目添加两次,则只需在该项目的数量属性上加+1即可。 但是,当我第二次单击它时,出现错误页面,提示:
LineItemsController#create中的NoMethodError
undefined method `+' for nil:NilClass
这是我的cart.rb:
class Cart < ActiveRecord::Base
has_many :line_items, dependent: :destroy
def add_product(product_id)
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity += 1
Rails.logger.debug(current_item.quantity)
else
current_item = line_items.build(:product_id => product_id)
end
current_item
end
end
line_item的数量属性为整数类型。 应该可以在上面加上整数,对吗? 那就是我目前感到困惑的地方。
这是line_items_controller.rb中的“创建”方法:
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
@line_item.product = product
respond_to do |format|
if @line_item.save
format.html { redirect_to @line_item.cart,
notice: 'Line item was successfully created.' }
format.json { render json: @line_item,
status: :created, location: @line_item }
else
format.html { render action: "new" }
format.json { render json: @line_item.errors,
status: :unprocessable_entity }
end
end
结束
有任何想法吗?
干杯
我认为这是因为current_item没有任何数量。 可能没有默认值。 您期望它为0,但实际上为nil
。
我设置了默认值,并确保该列不能为nil。 另外,您可以定义一个before_create
方法,该方法将在保存之前将该值设置为0(如果为nil)。
解决此问题的另一种方法是确保您那里没有零:
current_item.quantity = current_item.quantity.blank? ? 1 : current_item.quantity + 1
这表示current_item.quantity为null。 这可以是Integer,但在数据库中存储为null。 如果是这样,您可以在迁移过程中默认设置一个值,或者在首次创建时可以将数量值设置为1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.