Handle ActiveRecord::RecordNotFound More Elegantly

Balaji D Loganathan
Spritle Software
Published in
1 min readApr 19, 2016

Most of us usually handle the Active Record Not Found error in ApplicationController and then redirect it to a generic view page. I found a different and more efficient way to handle it.

Instead of handling the error at ApplicationController level handle it at your Model Controller. Lets you have a controller called PostsController for the model post, then add the line rescue_from ActiveRecord::RecordNotFound, with: :handle_record_not_found in it and define the method implementation in your controller.

class PostsController < ApplicationController
before_action goes_here
rescue_from ActiveRecord::RecordNotFound, with: :handle_record_not_found
def index
end

def show
end
...
def handle_record_not_found
# Send it to the view that is specific for Post not found
render :not_found
end
end

The key benefit here is you can have a specific view for every Model you have and you can show customised not found message.

--

--