ruby NoMethodError(nil:NilClass 的未定义方法 `[]')

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10810311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:09:35  来源:igfitidea点击:

NoMethodError (undefined method `[]' for nil:NilClass)

ruby

提问by Stewart Knapman

I have a very odd instance of this error:

我有一个非常奇怪的错误实例:

NoMethodError (undefined method `[]' for nil:NilClass):
app/controllers/main_controller.rb:150:in `block in find_data_label'
app/controllers/main_controller.rb:149:in `each'
app/controllers/main_controller.rb:149:in `find_data_label'
app/controllers/main_controller.rb:125:in `data_string'
app/controllers/main_controller.rb:35:in `catch'

Whats weird is that the line 150, where it says the error is, is inside a loop and executes perfectly 11 times before it decides to error out. I am out of ideas as to why it would work fine but fail one line before what would effective be the loop where the if statement returns true.

奇怪的是,第 150 行,它说错误所在,在一个循环内,在它决定出错之前完美地执行了 11 次。我不知道为什么它可以正常工作,但在 if 语句返回 true 的循环有效之前一行失败。

This is the code:

这是代码:

  def find_data_label(label)
    @fields.each do |f|
      puts "f[:field_data]['Title'] = #{f[:field_data]['Title']}" # <--- line 150
      if f[:field_data]['Title'] == label
        return f
      end
    end
  end

And this is the output before I get the error:

这是我收到错误之前的输出:

f[:field_data]['Title'] = Name
f[:field_data]['Title'] = Name
f[:field_data]['Title'] = Mobile number
f[:field_data]['Title'] = Email
f[:field_data]['Title'] = Date of birth
f[:field_data]['Title'] = Gender
f[:field_data]['Title'] = Street name
f[:field_data]['Title'] = Street number
f[:field_data]['Title'] = My local Puckles store is in
f[:field_data]['Title'] = Suburb
f[:field_data]['Title'] = Postcode
Completed 500 Internal Server Error in 2047ms

Thanks in advance for any help.

在此先感谢您的帮助。

采纳答案by Hck

One of your @fields elements doesnt contain Title in :field_data. Try inspecting @fields before calling @fields.each:

您的@fields 元素之一在:field_data 中不包含标题。在调用之前尝试检查@fields @fields.each

Rails.logger.warn '-'*40
Rails.logger.warn @fields.inspect

Check the server logs to see what elements you have in @fields.

检查服务器日志以查看@fields 中有哪些元素。

回答by Joe H

For that error, see also: http://mongoid.org/en/mongoid/docs/tips.html

对于该错误,另请参见:http: //mongoid.org/en/mongoid/docs/tips.html

e.g.maybe you're using MongoID and an older version of Ruby.

例如,也许您正在使用 MongoID 和旧版本的 Ruby。