1

I know from the rails documentation that find will result in a RecordNotFound error. However, the find_by method simply returns nil if a record is not found. Returning nil seems more intuitive to me and safe in general, so I am wondering if there is any benefit in using the find method over the find_by method?

For example, what is the difference between the following:

myRecord.find(1)

and

myRecord.find_by(id: 1) 

If the only difference is that find raises an error when a record isn't found, I don't really see the benefit in using find.

EDIT

For all the people that jumped on my question and said that it had been already answered, you are wrong. I clearly stated that I knew find returns an error when a record is not found (which is what everyone else emphasizes in their answers) and that find_by returns nil. I want to know if there are any other differences.

Community
  • 1
  • 1
Mark
  • 9,718
  • 6
  • 29
  • 47
  • https://stackoverflow.com/questions/15185919/whats-the-difference-between-find-where-and-find-by-id possible duplicate – Suhail Purkar Jul 28 '17 at 22:29
  • Possible duplicate of [What's the difference between find, where and find\_by\_id?](https://stackoverflow.com/questions/15185919/whats-the-difference-between-find-where-and-find-by-id) – Suhail Purkar Jul 28 '17 at 22:29
  • I apologize for my comment. I'm glad you found a satisfactory answer. Good luck! – jvillian Jul 29 '17 at 00:01

1 Answers1

4

In your specific example there is little difference between the two of them other than the error vs nil which you mention. Whether you want to handle an error or nil is totally up to you.

For a great explanation of understanding when an error is preferable to nil and vice versa read this.

If you are searching by an attribute other than id using find will not work as it can only access elements by their id.

manzhikov
  • 3,778
  • 3
  • 20
  • 22
ecarlin
  • 1,163
  • 8
  • 8
  • Thank you for linking to that SO question. DHH has a really good explanation as you said he did. Everyone else who commented on my question clearly didn't understand the intent of my question. Thanks. – Mark Jul 28 '17 at 22:43
  • Sure thing. You can also see the source code through the documentation if you want to get into the implementation differences between the two. https://apidock.com/rails/ActiveRecord/Base/find/class . Scroll down and click on "show source" – ecarlin Jul 28 '17 at 22:47