NoMethodError(nil的未定义方法`’:NilClass)

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

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' 

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

这是代码:

  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 

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

 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 

在此先感谢您的帮助。

你的一个@fields元素不包含Title in:field_data。 在调用@fields.each之前尝试检查@fields.each

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

检查服务器日志以查看@fields中的元素。

有关该错误,另请参阅: http : //mongoid.org/en/mongoid/docs/tips.html

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