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?

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:


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

there are a few ways to protect from nil-calls:

check with if:

return book.ranking if book

use &&/and:

return book && book.ranking

use try (in Ruby 1.9 or with Rails/ActiveSupport):

return book.try(:ranking)

you should check if book is nil either

return book.ranking unless book.blank? and book.ranking.blank?

You can do it also this way:

return book.ranking unless book and book.ranking

or with andand gem:

return book.ranking unless book.andand.ranking


 ? undefined method `topics_path'
 ? undefined method `coordinates' for nil:NilClass
 ? Undefined Method in ruby on rails
 ? Undefined method, avatar and name for nil:NilClass
 ? undefined method `premium?' for nil:NilClass
 ? undefined method `default_image' for nil:NilClass
 ? C# WinForms - Determine when void method returns
 ? C# - Unable to add item to listview from method invoked from class
 ? GCC : Return statement from a void function in C
 ? How to call objective c method from c method iOS