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.
the book object is the one that is nil, not ranking. So having
return book.ranking unless book.nil?
should resolve the issue.
I would use try here:
book.try(:ranking)
If book or ranking is nil then nil will be returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With