0

我有一个名为 的模型quiz,它有很多questions模型。我想添加某种逃避处理,以便当用户在quiz_idURL 中输入错误时,将呈现错误页面。

我写了一些辅助方法QuestionsController来处理异常:

private
def render_error(message)
    @error_message = message
    render 'error'
end

def active_quizzes_safe
    active_quizzes = Quiz.active_quizzes(current_user.id)
    render_error('Sorry! The request is invalid! Please log in again!') if active_quizzes.nil?
    active_quizzes
end


def active_quiz_safe(quiz_id)
    active_quiz = active_quizzes_safe.where(id: quiz_id).first
    render_error('The quiz does not exist or you are not allowed to take this quiz!') if active_quiz.blank?
    active_quiz
end

这是QuestionsController有问题的操作:

def show_quiz
  if current_user
    @quiz = active_quiz_safe(params[:quiz_id])
    @questions = @quiz.questions
  end
end

因此,如果:quiz_idURLlocalhost:3000/MY_URL/:quiz_id中的 不正确(即找不到记录),则该方法应呈现错误页面render_error。然而,当我累错了:quiz_id,我得到了undefined method 'questions' for nil:NilClass。我想这是因为@questions = @quiz.questionsinshow_quiz方法。

但是,执行是否应该在动作之后停止render_error,也就是之前@questions = @quiz.questions?为什么@questions = @quiz.questions还是被执行?

另外,有没有标准的方法来处理这样的 nil:NilClass 错误?

谢谢!!

4

2 回答 2

0

调用render方法不会停止操作。所以你应该仔细设计你的动作,以确保你在渲染后立即返回。像这样:

def show_quiz
  if current_user
    active_quizzes = Quiz.active_quizzes(current_user.id)
    if active_quizzes.nil?
      render_error('Sorry! The request is invalid! Please log in again!')
    else
      @quiz = active_quizzes_safe.where(id: quiz_id).first
      if @quiz.blank?
        render_error('The quiz does not exist or you are not allowed to take this quiz!')
      else
        @questions = @quiz.questions
      end
    end
  end
end

但在这种情况下,我认为最好使用一些异常控制,如下所示:

def show_quiz
  if current_user
    active_quizzes = Quiz.active_quizzes(current_user.id)
    @quiz = active_quizzes_safe.find(quiz_id)
    @questions = @quiz.questions
  end
rescue ActiveRecord::RecordNotFound
  render_error 'The quiz does not exist or you are not allowed to take this quiz!'
end
于 2013-08-08T15:11:06.040 回答
0

查看您的public/404.html, public/422.html and public/500.html文件。如果发生错误,Rails 将自动重定向。所以我认为你不需要手动处理异常,除非你有特定的情况。要测试和查看此错误页面,请在生产中运行应用程序bundle exec rails s RAILS_ENV=production

于 2013-08-08T16:14:41.193 回答