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
Yes, just do:
Challenge.find_by_id(10)
For Rails 4 and 5:
Challenge.find_by(id: 10)
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
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
You can try this Challenge.exists?(10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With