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! While you're at it, check out some resources Treehouse students have shared here.
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 trialIsmail Malik
10,131 PointsWhy 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
2 Answers
Jay McGavren
Treehouse TeacherBecause your 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 set_post
within show
(which will cause any exceptions to propagate up until they reach the show
method's rescue
clause), or duplicate the @post = Post.find(params[:id])
code within show
.
Ming King
6,519 PointsI 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?