am-rails
am-rails

Reputation: 1473

How to Handle Nil Errors in Rails?

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?

Upvotes: 0

Views: 1602

Answers (3)

Marek Takac
Marek Takac

Reputation: 3038

Interesting approach is using nil objects, although they are not suitable for every situation...

Upvotes: 0

Raindal
Raindal

Reputation: 3237

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

Upvotes: 3

Mark Swardstrom
Mark Swardstrom

Reputation: 18070

One of my favorite view rendering methods:

http://apidock.com/rails/Object/try

Upvotes: 1

Related Questions