One of the best things I love about Ruby is the vast enumerable module. It makes sorting — or iterating — through data so much easier and I can write much dryer code without having to incorporate countless loops. There is definitely a handful of them that I’ve naturally memorized, but as I am now progressing from the basics of Object-Oriented Ruby to Object-Relational Mapping, a whole new set of methods have come flooding my way through the ActiveRecord gem.
Although they do not perform exactly the same, I am happy to discover that ActiveRecord has some relatively mirroring methods when handling data from databases.
Below, I will be going over some common Ruby enumerables and their ActiveRecord method counterparts.
select/find_all & where
select, or its alias
find_all, is easily one of my most used enumerable. As the name suggests, it will select based on a stipulated condition and return an array containing all elements that return true.
ActiveRecord’s counterpart is
where will accept a condition and return a relational object if there is a match. As it is a relational object, we also grant ourselves access to any associated data. In the example below, we are trying to find the student named “Harry”. Since it is a relational object associated with other objects in the same student table, we can also grab the primary key (id).
SIDE NOTE: It’s important to note that ActiveRecord also responds to a
select method. However, it is not synonymous to
where, as it is used to retrieve all fields related to the attribute.
So, what if I only need to see each finding once and want to remove all duplicates? It’s not shown in the example above, but if there were multiple ‘Harry’s’ in the students array, Ruby would have returned all the ‘Harry’s’ present.
To remove all duplicates, we would use the enumerable
distinct method for ActiveRecord would yield comparable results. Instead of returning all records associated with an attribute, it will only return a single record per unique attribute.
Student.select(:name) example again, ActiveRecord will return multiple records with the same name, if present. Whereas, with
distinct, only one record will be returned per distinct name.
find/detect & find_by
Another handy enumerable often used is
find, or its alias
detect. In ActiveRecord,
find_by will perform similarly. These methods will all return the first result that returns true.
Here, I use
find_by to return values of the first instance that meets the criteria (ie. last_name). This is fine if the student, Ron Weasley, was who I wanted to retrieve. However, if there are multiple records in my table with students with the last name ‘Weasley’, I can make my
find_by criteria more limiting.
Since there is only one female of the Weasley children, the first instance meeting my new criteria now resulted in ‘Ginny’.
SIDE NOTE: Similar to the
select method above, ActiveRecord also responds to a
find method. Unlike the
find in ActiveRecord is used to retrieve an object based on their primary key (id).
sort_by & order
When the enumerable
sort_by is used, elements are sorted by an attribute and returned in an array. Similarly, the
order method in ActiveRecord also returns an array after sorting through and ordering an object by an attribute.
In the example above, the
sort_by enumerable is used to sort each name according to ascending length. In the example below, the
order method will sort the student names by alphabetical order.
min & minimum/max & maximum
This one is pretty self-explanatory. The enumerables
max will return the object with the minimum and maximum value, respectively. Whereas ActiveRecord’s minimum will find the lowest value of a field in your table, and the maximum will find the highest value.
include? & includes
Last but not least, there’s
Like those tricky side notes mentioned above, they yield very different results despite the similar name. While
include? iterates to return true if the given object is present,
includes, in ActiveRecord, specify which relational data to be included in the result. This relational data can then be further used for associations without additional database queries.
Let’s take a look at the
include? enumerable first:
Now let’s compare it to
In this example, the
includes method is used to retrieve student addresses. Since the city is also associated with each address, we’re able to access it without another additional query.
Now, if you were still wondering if
include? actually did have an ActiveRecord equivalent, it does.
exists? performs similarly in that it returns true if a record exists in the table that meets the conditions given, or match the id.
While not completely synonymous, drawing these connections was a great way for me to learn the ActiveRecord methods. Jumping from one syntax to another can get confusing at times, especially if you’ve just started your coding journey as I have. If typos are as common for you, as it is for me, then you’ve learned that every letter and character matters in your code. Hopefully, this little transitioning cheat sheet will come to your rescue at times of need.
Active Record Query Interface - Ruby on Rails Guides
Active Record Query InterfaceThis guide covers different ways to retrieve data from the database using Active…
Sorts using a set of keys generated by mapping the values in enum through the given block. The result is not guaranteed…
Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]). If one or…