Whats a good way to avoid nil lookup errors

When navigating to: http://localhost:3000/users/12

Whats a good way of avoiding the error: "Couldn't find User with
ID=12", which happens when i try to display a page of user_id 12 that
doesnt exist in the database.

Instead of showing the error. id like to show a page that says: "This
user does not exist"

Someone suggested using rescue_from. Is this the best solution for
this? Or are there better alternative approaches?

def show
  @user = User.find(params[:id])
rescue ActiveRecord::RecordNotFound
  redirect_to users_path, :alert => "This user does not exists"

One of the solutions would be to use redirect_to and flash[:notice]

@user = User.find(1)
unless @user
  flash[:notice] = "can't find user with given id"
  redirect_to users_path

I won't say it's the best but it's still a solution :slight_smile:

Yes but, it will never reach "unless." The system fails after @user =
User.find(1) since Active Record is trying to find a record that does
not exists

@user = User.find(1) if User.exists?(1)

I don't like doing two lookups for one record, but it works

What about
@user = User.find(:first, :conditions => {:id => 1})
if (@user)
   blah, blah, blah

It's longer to type, but returns nil if the user doesn't exist.

Ugis almost has it. Try this

@user = User.find_by_id(1)
unless @user
  flash[:notice] = "can't find user with given id"
  redirect_to users_path

ActiveRecord::Base#find_by_id is a dynamic finder that will work just like the line Simon has above--nil if there is no record found.


Rob Biedenharn
Rob@AgileConsultingLLC.com http://AgileConsultingLLC.com/
rab@GaslightSoftware.com http://GaslightSoftware.com/

So this would be the convention right? not by using rescue_from. Is
this right?

Hi Christian

Hi Paul. but wouldnt that redirect to users_path on any activerecord
not found event?

Good call on that find_by_id. Noted to myself :slight_smile:

nope, only within the action.