我目前正在研究我的项目,并且我是Ruby on Rails中的新成员。
我与购物车的工作,以相同组产品中的单行项 ,把我带到这个错误:意外的零对象
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+
我不明白为什么创建的方法无法找到
line_item_controller。 RB:
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
respond_to do |format|
if @line_item.save
format.html { redirect_to(@line_item.cart,
:notice => 'Line item was successfully created.') }
format.xml { render :xml => @line_item,
:status => :created, :location => @line_item }
else
format.html { render :action => "new" }
format.xml { render :xml => @line_item.errors,
:status => :unprocessable_entity }
end
end
end
Cart
所述模块的内部:
def add_product(product_id)
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
current_item
end
和我的观点是购物车显示的是
<% for item in @cart.line_items %>
<li><%= item.quantity %> × <%= item.product.title %></li>
<% end %>
编辑:
我认真,我不知道发生了什么,但是当我键入:
def add_product(product_id)
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
current_item
end
此行要准确它进行得很好
current_item.quantity += 1
有人可以解释刚发生的事情吗?
貌似数量不具有价值有时。你的物品模型是否有验证,确保它必须包含某些东西?否则看看你的分贝,看看是否有任何缺少数量的记录。 – 2012-02-19 15:31:48
@ thorstenmüller是的,它现在工作正常问题是在我第一次尝试添加项目它会产生一个零不能被强制为BigDecimal错误,但当我回到主页并点击第二次尝试它的工作罚款,但没有算我的第一次尝试 – Led 2012-02-21 09:31:15