What is the best way to handle the error then ID is not found? I have this code in my controller:
def show
@match = Match.find(params[:id])
end
I was thinking about something like this:
def show
if @match = Match.find(params[:id])
else
render 'error'
end
end
But I still get:
ActiveRecord::RecordNotFound in MatchesController#show
Couldn't findMatch with 'id'=2
Why?
What is the correct solution?
Rescue it in the base controller and leave your action code as simple as possible. You don't want to deal not found exception in every action, do you?
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
def render_404
render :template => "errors/error_404", :status => 404
end
end
By default the find
method raises an ActiveRecord::RecordNotFound
exception. The correct way of handling a not found record is:
def show
@match = Match.find(params[:id])
rescue ActiveRecord::RecordNotFound => e
render 'error'
end
However, if you prefer an if/else approach, you can use the find_by_id
method that will return nil:
def show
@match = Match.find_by_id(params[:id])
if @match.nil? # or unless @match
render 'error'
end
end
You can use find_by_id method it returns nil instead of throwing exception
Model.find_by_id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With