exception handling - How to Handle Nil Errors in Rails? -
what correct way deal nil errors in rails? errors like:
nomethoderror (undefined method `questions' nil:nilclass):
for example, let's have chapters in app each have question. call question previous chapter within current question, write following code in question.rb:
def previous_question self.chapter.previous.question end
this might cause above-mentioned error, write method in model check if lead nil result:
def has_previous_question? self.chapter , self.chapter.previous , self.chapter.previous.question end
if make sure call before calling previous_question
, can work, looks ridiculous. there better way deal nil errors in rails?
i not tell right way way of handling kind of situation:
def previous_question self.chapter.previous.try(:question) end
that way there won't error, if there no previous chapter, method return nil.
if want return else in case nil, can write:
def previous_question self.chapter.previous.try(:question) || returning_this_value_instead end
side note: don't need use self in kind of situation:
def previous_question chapter.previous.try(:question) || returning_this_value_instead end
Comments
Post a Comment