2011-04-15 50 views
0

嗨,对不起,如果这是一个愚蠢的问题,真的我是ROR世界的新手,我正在努力学习。没有对象的NoMethodError

我阅读使用Rails电子书的敏捷Web农业开发并按照本书的程序我得到的股票与此错误:

NoMethodError in Line itemsController#create

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.

这是车型号

class Cart < ActiveRecord::Base 
    has_many :line_items, :dependent => :destroy 

    def add_product(product_id) 
    current_item = line_items.where(:product_id => product_id).first 
    if current_item 
     current_item.quantity += 1 
    else 
     current_item = LineItem.new(:product_id => product_id) 
     line_items << current_item 
    end 
    current_item 
    end 
end 

这是行项目控制器正在调用哪种方法

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.cart, :status => :created, :location => @line_item } 
     else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @line_item.errors, :status => :unprocessable_entity } 
     end 
    end 
    end 

Rails版本3.0.5 红宝石版本1.8.7

任何建议?你能看到什么是错的吗? 谢谢

+1

请发帖行号。 – 2011-04-15 18:55:07

+1

发布堆栈跟踪的完整错误,您忽略了关键信息。 – 2011-04-15 19:41:22

+0

在发布错误的行号之前,您不会获得任何有用的帮助。 – sawa 2011-04-15 19:50:35

回答

1

问题是你正在调用一个方法的对象是零。该错误消息应该有一个行号,应该指向导致问题的有害代码行。

只是一个猜测,但可以current_cart返回零?那将是我最初的预感,但如果你能突出显示哪条线是错误的原因,那将会有所帮助。

0

NoMethodError意味着您正在调用未针对您正在调用方法的类的实例定义的方法,在这种情况下,您尝试调用方法的对象的类是NilClass 。如果你不确定什么对象是零,你可以总是问012b,但是,正如另一个答复者所说,它应该告诉你哪一行包含错误(如果不是确切的语法)。

2

当它报告一个无对象的NoMethodError时,这意味着你正在调用一个方法的对象不存在。在此,可能是@cart@line_item没有数据,具体取决于发生错误的行号。因此,它可能是

@cart = current_cart 

......或者......

@line_item = @cart.add_product(product.id) 

没有返回一个有效的对象。看看这些方法。