Ruby - NoMethodError (undefined method for nil:NilClass):
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 ruby interpreter throwed that exception. I see the two main reason for it:
-
self
keyword variable hasnil
value, I believe not in the reason, because you do a call from a controller, as you've saidApplicationController
. To make sure thatself
isn'tnil
, 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.
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.
Dodinas
Updated on July 09, 2022Comments
-
Dodinas almost 2 years
I'm having some difficulty trying to figure out what I am doing wrong. My
ActiveRecord
query is returningnil
which I think is causingNoMethodError
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?