Comparable Ruby Enumerables and ActiveRecord Methods

Photo by Safar Safarov on Unsplash

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.

select is being used to iterate through the students array and only returns with the student named “Harry”.

ActiveRecord’s counterpart is where. 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).

If we are trying to find the student named ‘Harry’, .where will tell AR to look through the Student model and find the attribute matching the name “Harry”.

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.

The select method in AR will retrieve all values under the name column

uniq/distinct

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 uniq.

Even though ‘Harry’s’ name is listed three times in the array, his name is only returned once.

The 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.

Using our 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.

Using .distinct will return one record 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.

In this code block, I want Ruby to find and return only the first student matching “Ron”.

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 myfind_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 enumerable, find in ActiveRecord is used to retrieve an object based on their primary key (id).

.find in ActiveRecord is used to retrieve an object through their 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.

sort_by returns and array after sorting elements 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.

Will order an attribute (ie. name).

min & minimum/max & maximum

This one is pretty self-explanatory. The enumerables min and 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.

.max will return the highest value
.min will return the lowest value
The .maximum and .minimum methods will access the stipulated attributes column (ie. age) and return the highest, and the lowest value, respectively.

include? & includes

Last but not least, there’s include? and includes.

NOT!

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:

include? is used to see if “Hermione” is included somewhere in this array. It is, so it returns true.

Now let’s compare it to includes:

In this example, theincludes 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.

If any student named “Harry” exists, return true.

Conclusion

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.

Resources

Full Stack Software Engineer