mzakzook
Posted on April 12, 2020
Through the last several Rails projects I've built, Active Record has been the resource that allows me to easily link objects to a database, and write queries that improve the functionality and efficiency of my code. Active Record provides query logic that closely resembles SQL (structured query language) queries, but can typically be written with fewer lines and is more intuitive, for me, because it follows Ruby syntax.
Active Record is an Object Relational Mapping (ORM) system. This means that it handles the storing of your data to tables in a relational database management system and allows for the creation and retrieval of your data through language specific commands.
One of my first projects using Active Record was a brewery search and bookmarking CLI (command line interface) app. The goal was to allow a user to search for any brewery in California, add a bookmark, write a review and save a favorite drink. Below, I've included an Active Record query that finds the current user's favorite drink.
fav_drink = Bookmark.select('favorite, count(favorite) as cnt').where('user_id = ?', self.id).group('favorite').order('cnt DESC').first
For anyone with SQL experience, the statement above should be easy to read. I'm first declaring a variable, 'fav_drink', and setting it equal to an Active Record query on Bookmarks. The query selects the values, 'favorite' and a custom value, 'cnt' which is meant to keep the total of favorites for each drink. The query then limits results to bookmarks where the user id is equivalent to the current user's id. It then groups the results by the favorite drink that was entered, which leaves an array of objects representing each drink that the current user has favorited and its corresponding count. The query then sorts the results in descending order based on the value of each drink's count, and returns the first result (the drink with the highest count).
The ruby alternative to this statement would require more lines of code and have much worse performance when dealing with large quantities of data.
For some more complicated projects and heavy data analysis, it is my understanding that many still prefer writing raw SQL and find that ORM systems create performance and integration issues. With that being said for small teams that do not have a SQL expert, an ORM system, like Active Record, allows for intuitive and efficient data mapping and querying.
Posted on April 12, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.