What is the correct way to deal with nil errors in Rails? I often get errors like:
NoMethodError (undefined method `questions' for nil:NilClass):
For example, let's say I have chapters in my app which each have a question. I would like to call the question from the previous chapter from within the current question, so I write the following code in question.rb:
def previous_question
self.chapter.previous.question
end
This might cause the above-mentioned error, so I write a method in the model to check if this will lead to a nil result:
def has_previous_question?
self.chapter and self.chapter.previous and self.chapter.previous.question
end
If I make sure to call that before calling previous_question
, it can work, but it looks ridiculous. Is there a better way to deal with nil errors in Rails?
I could not tell this is THE right way but it is another way of handling this kind of situation:
def previous_question
self.chapter.previous.try(:question)
end
That way there won't be any error, if there is no previous chapter, the method will simply return nil .
If you want to return something else in case it is actually nil, you can write:
def previous_question
self.chapter.previous.try(:question) || returning_this_value_instead
end
Side note: you don't need to use self in that kind of situation:
def previous_question
chapter.previous.try(:question) || returning_this_value_instead
end
One of my favorite view rendering methods:
有趣的方法是使用nil对象 ,尽管它们并不适合所有情况。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.