Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.Start your free trial
Ismail Malik10,131 Points
Why rescue ActiveRecord::RecordNotFound is not working with before_action?
Why rescue ActiveRecord::RecordNotFound is not working when using before_action to :set_post to the show action method???
class PostsController < ApplicationController before_action :set_post, only: [:show, :edit, :update, :destroy] def show rescue ActiveRecord::RecordNotFound flash[:notice] = "We couldn't find that Post." redirect_to action: :index end private def set_post @post = Post.find(params[:id]) end
Jay McGavrenTreehouse Teacher
rescue clause is in the
show method, it will only rescue exceptions thrown within the
show method. You should remove
:show from the
before_action and either call
show (which will cause any exceptions to propagate up until they reach the
rescue clause), or duplicate the
@post = Post.find(params[:id]) code within
Ming King6,519 Points
I think put the rescue inside the set_page private method would be good. def set_page @page = Page.find(params[:id]) rescue ActiveRecord::RecordNotFound flash[:notice] = "We couldn't find that page" redirect_to action: :index end
But the flash[:notice] didn't show as expected. Why?