rescue from ActiveRecord::RecordNotFound in Rails
If you want to use the rescue statement you need to use find()
in a way it raises exceptions, that is, passing the id you want to find.
def edit
@post = Load.scoped_by_user_id(session[:user_id]).find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:notice] = "Wrong post it"
redirect_to :action => 'index'
end
You can also use ActionController
's rescue_from
method. To do it for the whole application at once!
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
def record_not_found
render 'record_not_found' # Assuming you have a template named 'record_not_found'
end
end