Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle error when ID is not found?

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?

like image 469
Jensky Avatar asked Sep 01 '15 09:09

Jensky


3 Answers

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
like image 128
xdazz Avatar answered Oct 17 '22 07:10

xdazz


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
like image 44
Francesco Boffa Avatar answered Oct 17 '22 08:10

Francesco Boffa


You can use find_by_id method it returns nil instead of throwing exception

    Model.find_by_id
like image 1
Faizan Avatar answered Oct 17 '22 09:10

Faizan