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

38,333

Solution 1

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.

Solution 2

Please run the below line in your console:

@available_number = UserNumber.where.not(:user_num => @number_exclude_list)

it returns an ArgumentError: wrong number of arguments (0 for 1+) since it is not the way to check NOT IN condition in Rails activerecord.

Replace it with:

User.where('user_num NOT IN (?)',@number_exclude_list)

and then do:

if @available_number == nil
   inform_user_empty
else
   do_my_other_function
end

Hoep that will resolve the issue. Please let me know if it really helped you.

Share:
38,333
Dodinas
Author by

Dodinas

Updated on July 09, 2022

Comments

  • Dodinas
    Dodinas almost 2 years

    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?