13

I am working with the following piece;

def index
  @user = User.find(params[:id]) 
  rescue
    flash[:notice] = "ERROR"
    redirect_to(:action => 'index')
  else 
    flash[:notice] = "OK"
    redirect_to(:action => 'index')
end

Now I either case whether I have a correct ID or not, I am always getting "OK" in my view, what am I doing wrong?

I need that when I have no ID in the DB to show "ERROR". I have also tried to use rescue ActiveRecord::RecordNotFound but same happens.

All help is appreciated.

Adnan
  • 25,882
  • 18
  • 81
  • 110
  • Is this actual code from your app? As it stands it looks like you are redirecting back to the same action (index) which will result in an infinite loop. – mikej Apr 02 '10 at 15:47

3 Answers3

37

All code after the end of the rescue block is interpreted only if there are no returns in the rescue block. So you can call return at the end of your rescue block.

def index
  begin
    @user = User.find(params[:id]) 
  rescue
    flash[:notice] = "ERROR"
    redirect_to(:action => 'index')
    return
  end
  flash[:notice] = "OK"
  redirect_to(:action => 'index')
end

or

def index
  @user = User.find(params[:id]) 
  # after is interpret only if no exception before
  flash[:notice] = "OK"
  redirect_to(:action => 'index')
rescue
  flash[:notice] = "ERROR"
  redirect_to(:action => 'index')
end

But in your case the better is to use rescue_from or rescue_in_public

like

class UserController < ApplicationController
  def rescue_in_public(exception)
    flash[:notice] = "ERROR"
    redirect_to(:action => 'index')
  end

  def index
    @user = User.find(params[:id]) 
    flash[:notice] = "OK"
    redirect_to(:action => 'index')
  end
end

But the using of rescue_in_public is not really good advice

quoo
  • 6,237
  • 1
  • 19
  • 36
shingara
  • 46,608
  • 11
  • 99
  • 105
4

Just an overall Rails Rescue answer:

I found this to be very cool:

@user = User.find(params[:id])  rescue ""
FastSolutions
  • 1,809
  • 1
  • 25
  • 49
-5

If there is no user with that id, then User.find will return nil. Returning nil is not an error case and will not trigger a rescue.

yfeldblum
  • 65,165
  • 12
  • 129
  • 169
  • 9
    I am pretty sure this is not right. `find` with an invalid ID will raise `ActiveRecord::RecordNotFound`. If you use one of the dynamic finders e.g. `User.find_by_name` with a value that doesn't match a record then that will return `nil`. See http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002263 – mikej Apr 02 '10 at 14:56
  • 1
    Well sir, I checked and you are correct. Thank you. The find call in the OP should actually raise, unless the code is actually `User.find(:first, params[:id])`. – yfeldblum Apr 02 '10 at 17:56