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

I have a very strange 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' 

It is strange that line 150, where the error is mentioned, is inside the loop and runs fine 11 times before it resolves the error. I do not know why it will work fine, but one line will not work until it is effective, this is a loop in which the if statement returns 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 result 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 your help.

+7
source share
2 answers

One of your @fields elements does not contain Title in: field_data. Try checking @fields before calling @fields.each :

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

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

+4
source

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

for example , maybe you are using MongoID and an earlier version of Ruby.

+1
source

All Articles