7

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.

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.

Stewart Knapman
  • 155
  • 1
  • 2
  • 11
  • Possible duplicate of [How to avoid NoMethodError for missing elements in nested hashes, without repeated nil checks?](https://stackoverflow.com/questions/4371716/how-to-avoid-nomethoderror-for-missing-elements-in-nested-hashes-without-repeat) – user513951 Mar 14 '19 at 03:43

2 Answers2

4

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

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

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

Hck
  • 9,087
  • 2
  • 30
  • 25
  • Yup that was it. For some reason the output was all segmented and out of order, but after piecing it together it showed :field_data => nil. Thanks for your help. – Stewart Knapman May 30 '12 at 08:33
1

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

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

Nikhil
  • 16,194
  • 20
  • 64
  • 81
Joe H
  • 11
  • 1