Saving Time With Active Record

Alex Davis
3 min readMay 10, 2022

Active Record — I never thought I would love something more than React, but it might be right up there with it!

The simplicity of Ruby code, paired with the versatility of Active Record methods, is hard to beat. So, for this week’s blog post, I have decided to talk about some of my favorite Active Record methods.

To begin, a short speel about what Active Record is. Active Record is an object-relational mapping framework full of unique mechanisms that allow developers to represent models and their data, associations between them, show inheritance hierarchies through related models, and more.

We access these mechanisms through ‘methods,’ Ruby’s version of a JavaScript function. Active Record methods work as finder methods that allow the developer to locate specific objects in the database. It works by passing arguments into each method to perform specific queries on your database without writing raw SQL. Of course, the SQL is still occurring, but it is all under the hood!

I have included a few methods with examples below and the corresponding SQL queries to show how much time Active Record saves us!

Where — works by:

  • filtering through the entire table
  • returns a new collection of data that meets the specifications
  • accepts arguments such as arrays, strings, hashes, and more!
Client.where("orders_count = '2'")
# SELECT * from clients where orders_count = '2';User.where(["name = ? and email = ?", "Joe", "joe@example.com"])
# SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';User.where(name: ["Alice", "Bob"])
# SELECT * FROM users WHERE name IN ('Alice', 'Bob')

Order — works by:

  • ordering our database in a specific way
  • returns an array with sorted by
  • accepts strings, symbols, and Arel(for more complicated expressions) as arguments
User.order(:name)
# SELECT "users".* FROM "users" ORDER BY "users"."name" ASCUser.order(email: :desc)
# SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
# by default, order is descending. replace 'desc' with 'asc' to order ascendingly

Join — works by:

  • performs joins across multiple tables on the arguments passed in

Single join:

User.joins(:posts)
# SELECT "users".*
# FROM "users"
# INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
  • multiple tables can be joined together

Multiple joins:

User.joins(:posts, :account)
# SELECT "users".*
# FROM "users"
# INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
# INNER JOIN "accounts" ON "accounts"."id" = "users"."account_id"

Nested joins:

User.joins(posts: [:comments])
# SELECT "users".*
# FROM "users"
# INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
# INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"

Each of the examples above are query methods, but Active Record also has aggregation methods such as:

Sum — works by:

  • calculates the sum of values on a given column
  • the value is returned with the same data type of the column
Person.sum(:age) # => 4562

Count — works by:

  • counts the records
  • can be used in conjunction with select or group
Person.count
# => the total count of all people
Person.count(:age)
# => returns the total count of all people whose age is present in database
Person.count(:all)
# => performs a COUNT(*)Person.select(:age).count
# => counts the number of different age values

These short examples are only scraping the surface of all that is possible with utilizing Active Record. All code examples were taken from the Ruby on Rails Active Record documentation. Thank you for reading!

--

--