learn about Where, Find, Find_by and Find_by!
First off congratulations! I’m assuming (which could backfire on me) that you are a newbie coder or you wanna refresher on your Ruby skills. The fact that you are this far in your understanding Ruby/Rails says a lot about how far you’ve come. Just wanna say your awesome!!
Any who! When it comes to building out a website or an app, you will run into situations quite often when you will need to call on or find the information to have a certain function work properly in your app.
For example, let’s say you are building an app that takes orders for baby narwal stuffed animals. (SOOOOO CUTE!)
You will probably have a need to have a way to FIND a customer or search through the orders and pull out all the order WHERE people ordered 5 or more narwhals because you want to send them a bonus gift.
Hopefully you see following the pattern:)
Luckily for us, ActiveRecord has given us some handy dandy methods to make that search or query that much easier.
There are a buttload if finder and query methods but in this article we’ll be covering Find, Find_by, find_by! and Where.
This method takes arguments. It will find the first record that matches the arguments we gave it. If the record can’t be found this method will simply return nil. It’s also important to note that there’s no assumed ordering. Meaning, if order matters to you, be sure to implement it yourself.
This method takes arguments. It’s typically used to find by the primary key id in the database. With the find method, it can either be a specific id (1), a list of ids (8 9, 10), or an array of ids ([8, 9, 10]). If the record can’t record can’t be found for all of the listed ids, then an error of RecordNotFound will be raised. If the primary key is an integer, find by id coerces its arguments using to_i.
This method takes arguments as well. The only difference between find_by and find_by! Is that that if no record is found, raises an ActiveRecord::RecordNotFound error.
This method is a lot like the other three but is classified as a querymethod and is more of a catch all. This method takes an argument as well. It can be a string, array, or hash. (It can also be chained) With where we are given the ability to generate SQL of a form and specify the conditions we want to be returned.
And that’s it! Hope this little article helps.:)