如何处理Rails中的Nil错误?

时间:2013-05-21 20:31:25

标签: ruby-on-rails exception-handling error-handling runtime-error null

在Rails中处理nil错误的正确方法是什么?我经常会遇到错误:

  

NoMethodError(nil的未定义方法`questions':NilClass):

例如,假设我的应用程序中有章节,每个章节都有一个问题。我想在当前问题中调用前一章中的问题,所以我写下以下代码:rb:

def previous_question
 self.chapter.previous.question
end

这可能会导致上述错误,所以我在模型中编写一个方法来检查这是否会导致nil结果:

def has_previous_question?
 self.chapter and self.chapter.previous and self.chapter.previous.question
end

如果我在调用previous_question之前确保调用它,它可以工作,但它看起来很荒谬。有没有更好的方法来处理Rails中的nil错误?

3 个答案:

答案 0 :(得分:3)

我不知道这是正确的方法,但它是处理这种情况的另一种方式:

def previous_question
  self.chapter.previous.try(:question)
end

这样就没有任何错误,如果没有上一章,该方法只会返回 nil

如果你想要返回别的东西,以防它实际上是零,你可以写:

def previous_question
  self.chapter.previous.try(:question) || returning_this_value_instead
end

旁注:在这种情况下你不需要使用self:

def previous_question
  chapter.previous.try(:question) || returning_this_value_instead
end

答案 1 :(得分:1)

我最喜欢的视图渲染方法之一:

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

答案 2 :(得分:0)

有趣的方法是使用nil objects,虽然它们不适合所有情况......