What causes the NoMethodError: undefined method? Include? for nil: NilClass "

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

Recently, an application can run NoMethodError: undefined method 'include?' for nil:NilClassfor the following code:

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

However, this is incompatible. The vast majority of the time, turning to book works - an error occurs, perhaps in 2-4% of cases. If I change the code to book[:ranking]or book['ranking']instead book.ranking, it works 100% of the time.

Any ideas?

PS This problem occasionally occurred with other models and attributes ... and not just with the Book and Rank attribute.

+3
5

- , , . ,

return book.ranking unless book.nil?

.

+2

try :

book.try(:ranking)

book ranking - nil, nil.

+1

nil-:

, :

return book.ranking if book

&/:

return book && book.ranking

( Ruby 1.9 Rails/ActiveSupport):

return book.try(:ranking)
+1

,

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

:

return book.ranking unless book and book.ranking

andand gem:

return book.ranking unless book.andand.ranking
0
source

Source: https://habr.com/ru/post/1740181/


All Articles