ruby on rails 3 - How to handle exceptions caused by nil:NilClass -


i have model called quiz, has many questions models. want add kind of esception handling when user types in wrong quiz_id in url, error page rendered.

i wrote helper methods in questionscontroller handle exceptions:

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! request 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 not exist or not allowed take quiz!') if active_quiz.blank?     active_quiz end 

and here action in questionscontroller has problems:

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

so if :quiz_id in url localhost:3000/my_url/:quiz_id not correct(that is, record cannot found), error page should rendered render_error mothod. however, when tired wrong :quiz_id, got undefined method 'questions' nil:nilclass. guess because of @questions = @quiz.questions in show_quiz method.

however, execution supposed halt after render_error action, before @questions = @quiz.questions? why @questions = @quiz.questions executed anyway?

in addtion, there standard ways handle nil:nilclass errors this?

thank you!!

look in public/404.html, public/422.html , public/500.html files. rails automatically redirects if error occurs anyway. think don't need manually handle exceptions, except have specific case. test , view error pages run application in production bundle exec rails s rails_env=production.


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -