Introduction
In the beginning of my Rails journey, find_by
became the bane of my existence, and I didn't even know how, why, or what was happening. Everything was perfectly fine when testing out a new account or creating a new object after database migration. I mean, they were the first objects in the database. Of course everything would go well. Until it came down to testing gated content/permissions between two users...
What is find_by
?
This is probably the first question I should have asked myself. Don't you know what the say about assuming? I did a lot of that, and I paid for it with hours and hours of stubborn frustration. To begin with, find_by
isn't what you think it is. It returns the first item in the database. Even if you edit an item on a TODO list with an id
of 27, user_id
of 6, and description
of "Buy Chocolate Milk", using find_by
in your controller will return the very first item you didn't specifically query for. That's what find
is for.
What is find
?
It's how we retrieve the exact data we queried for, and the data must match the criteria. With find
, it doesn't loosely choose anything that might be related to the condition we pass in. This would have saved me hours of headache if I had given myself the time to understand them. But they have definitely changed the progress I've made in my projects ever since.
Ever heard of where
?
In my searches, I came across this super neat bonus. If you're like me and wondered what the purpose of it is compared to find
or find_by
, where
returns a collection of all items that match a certain criteria. If there are no results, it returns an empty object. Unlike the others which throw an exception error.
Conclusion
Sometimes, syntax doesn't mean what you think it means. If you make assumptions, you'll get some unexpected behavior. You'll have to do some research, but along the way you might learn about some tools that are a bit cooler and more useful than the one you're using. When in doubt, things go wrong for a good reason and it usually has something to do with what you don't understand about the code you're using.
Happy Tuesday!
Top comments (1)
find_by is only good in situations where you are actually doing #where then #first on top of the where.
That is when you should use #find_by.