2012-02-19 45 views
1

我目前正在研究我的项目,并且我是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 %> &times; <%= 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

有人可以解释刚发生的事情吗?

+1

貌似数量不具有价值有时。你的物品模型是否有验证,确保它必须包含某些东西?否则看看你的分贝,看看是否有任何缺少数量的记录。 – 2012-02-19 15:31:48

+0

@ thorstenmüller是的,它现在工作正常问题是在我第一次尝试添加项目它会产生一个零不能被强制为BigDecimal错误,但当我回到主页并点击第二次尝试它的工作罚款,但没有算我的第一次尝试 – Led 2012-02-21 09:31:15

回答

1

而不是current_item.quantity += 1尝试current_item.quantity = current_item.quantity.to_i + 1 我所做的是,如果current_item.quantitynilcurrent_item.quantity.to_i会= 0,否则它会得到current_item.quantity的整数值

+0

谢谢我再次使用current_item.quantity + = 1 错误,然后尝试你的代码后,它再次工作顺利:) – Led 2012-02-20 15:48:43

+0

不客气=) – mohamagdy 2012-02-21 08:37:43

+0

现在的问题是在我的第一个项目试图它产生一个零不能强制进入BigDecimal错误,但当我回到主页,并点击第二次尝试它工作正常,但没有算我第一次尝试 – Led 2012-02-21 09:32:20

0

从给定的代码,我怀疑只有跟着行current_item.quantity += 1。我猜这有时候是零,这就是为什么你会得到例外。

确保当你做以下的量的值初始化为1妥善

current_item = line_items.build(:product_id => product_id) 

注意:当你看日志,你可以找出其中引发异常的行号。检查该行中使用的变量并挖掘更多。