Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's causing "NoMethodError: undefined method `include?' for nil:NilClass"

I have a Book model in my Rails application, with various properties (aka columns in the book db table). One of these properties is "ranking".

Recently, may app has started to throw NoMethodError: undefined method 'include?' for nil:NilClass for the following code:

def some_method(book, another_arg)
  return book.ranking unless book.ranking.blank?
  ...
end

However, it's not consistent. The vast majority of the time, accessing book.ranking works -- the error is thrown maybe 2-4% of the time. If I change the code to book[:ranking] or book['ranking'] instead of book.ranking, it works 100% of the time.

Any ideas?

P.S. This problem has popped up intermittently with other models and attributes... not just Book and the ranking attribute.

like image 378
NudeCanalTroll Avatar asked Jun 19 '26 12:06

NudeCanalTroll


2 Answers

the book object is the one that is nil, not ranking. So having

return book.ranking unless book.nil?

should resolve the issue.

like image 124
Rob Di Marco Avatar answered Jun 21 '26 00:06

Rob Di Marco


I would use try here:

book.try(:ranking)

If book or ranking is nil then nil will be returned.

like image 29
Ryan Bigg Avatar answered Jun 21 '26 01:06

Ryan Bigg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!