I have received multiple identical questions from my readers, so I think it would make sense to dedicate a separate post to this issue.
What is the difference between this:
User.find(1)
vs
User.find_by_id(1)
and when to use one over the other ?
Great Question! The answer to this question lies in how they are handling exceptions.
When you use .find_by_id and object is not found, you won’t get an exception.
So code like this :
begin user = User.find_by_id(1) rescue ActiveRecord::RecordNotFound => e error_count += 1 end #error_count is 0
Will never reach your rescue block, because .find_by_id will just evaluate to nil.
Whereas this code:
begin user = User.find(1) rescue ActiveRecord::RecordNotFound => e error_count += 1 end #error_count is 1
will work out of the box because .find will raise an exception if record is not found.
Note: Workaround if you want to use find_by and raise an exception to use ‘!’:
user = User.find_by_id!(1)
Have something to add ? Please put your thoughts into comments! Want to be first to know when new post comes out ? Click Subscribe button below!
Cheers,
Anatoly

The post Difference between .find and .find_by in Rails 4 appeared first on My Programming Blog.