【问题标题】:NoMethodError with nil objectNoMethodError 与 nil 对象
【发布时间】:2011-04-15 18:31:50
【问题描述】:

您好,抱歉,如果这是一个愚蠢的问题,我真的是 ROR 世界的新手,我正在努力学习。

我正在阅读使用 Rails 电子书的敏捷 Web 开发,并按照本书程序进行操作,但出现此错误:

Line itemsController#create 中的 NoMethodError

当你没想到时,你有一个 nil 对象! 您可能期望有一个 Array 的实例。 评估 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 Ruby 版本 1.8.7

有什么建议吗?你能看出有什么问题吗? 谢谢

【问题讨论】:

  • 请张贴行号。
  • 使用堆栈跟踪发布完整错误,您忽略了关键信息。
  • 在您发布错误的行号之前,您不会获得任何有用的帮助。

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

当它在 nil 对象上报告 NoMethodError 时,这意味着您正在调用其方法的对象不存在。在这里,@cart@line_item 可能没有数据,具体取决于发生错误的行号。所以可能是这样的

@cart = current_cart

...或...

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      NoMethodError 表示您正在调用一个未为您正在调用其方法的类的实例定义的方法,在这种情况下,您尝试为其调用方法的对象的类是NilClass。如果您不确定什么对象是 nil,您可以随时使用 obj.class 询问 irb,不过,正如其他回答者所说,它应该告诉您哪一行包含错误(如果不是确切的语法)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-28
        • 1970-01-01
        • 2011-04-10
        相关资源
        最近更新 更多