Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find() with nil when there are no records

In my current rails program when I use something like

 user = User.find(10)

When there is no user with ID=10 , I will have exception like :

ActiveRecord::RecordNotFound: Couldn't find User with ID=10

Can I get nil instead of raising exception so when I do something like :

unless user = Challenge.find(10)
  puts "some error msg"         
end

I just want to get nil when there is no records and I don't want to use begin/rescue

Thanks

like image 906
Eqbal Avatar asked Mar 07 '12 15:03

Eqbal


4 Answers

Yes, just do:

Challenge.find_by_id(10)

For Rails 4 and 5:

Challenge.find_by(id: 10)
like image 186
apneadiving Avatar answered Nov 20 '22 11:11

apneadiving


In Rails 4, dynamic finders - such as find_by_id which was used in the accepted answer - were deprecated.

Moving forward, you should use the new syntax:

Challenge.find_by id: 10
like image 36
hattila91 Avatar answered Nov 20 '22 12:11

hattila91


you can do this a bit hackish, just use the ActiveRecord Query Interface.

this will return nil, instead of raising a Exception

  User.where(:id => 10).first
like image 15
beanie Avatar answered Nov 20 '22 12:11

beanie


You can try this Challenge.exists?(10)

like image 4
tonymarschall Avatar answered Nov 20 '22 12:11

tonymarschall