Ruby - NoMethodError (undefined method for nil:NilClass):

Dodinas picture Dodinas · Feb 11, 2014 · Viewed 38.1k times · Source

I'm having some difficulty trying to figure out what I am doing wrong. My ActiveRecord query is returning nil which I think is causing NoMethodError to be raised.

Here's what I have:

@number_exclude_list = ["1234567890", "2223334545"] 
@available_number = UserNumber.where.not(:user_num => @number_exclude_list)

Which returns an empty set of rows:

=> #<ActiveRecord::Relation []>

So, then I have:

if (@available_number.empty?)
   inform_user_empty
else
   do_my_other_function

But, I get:

`NoMethodError (undefined method 'inform_user_empty' for nil:NilClass)`

I have tried: @available_number.blank? and `@available_number.nil?

And I still get the same NoMethodError. Any ideas on what I am doing wrong here?

Answer

Малъ Скрылевъ picture Малъ Скрылевъ · Feb 11, 2014

The exception text NoMethodError (undefined method 'inform_user_empty' for nil:NilClass) says that is was a call to instance method #inform_user_empty of the nil class'es instance, and since nil has no instance method interpreter throwed that exception. I see the two main reason for it:

  1. self keyword variable has nil value, I believe not in the reason, because you do a call from a controller, as you've said ApplicationController. To make sure that self isn't nil, change the code to the following one:

    if @available_number.empty?
       p self
       self.inform_user_empty
    

    rerun the action, and look at the result.

  2. The exception has been thrown from another place. So you have to specify the full trace log in your post.