why use rescue nil?

Hey all,

I saw this piece of code:

@user = User.find(params[:user_id]) rescue nil

why rescue with a nil here? If the user is not found, it will be nil
anyway.

if the record is not found the find() throws an exception.

http://api.rubyonrails.org/classes/ActiveRecord/RecordNotFound.html

ok I thought it would return nil

thanks for response

Just a reminder: it’s just specific with the find(). find_by_* will return nil unless you add a ! (e,g, find_by_name!()) then it also returns the exception

It would take 30seconds to try it out in a console...

Alson you could just use where:
@user = User.where(:id => params[:user_id]).first

Because the author forgot about find_by_id, which would accomplish the exact same thing (returning nil if no record was found).

–Matt Jones