Want to see the full-length video right now for free?

Sign In with GitHub for Free Access


In this course, we're going to go on a deep dive into ActiveRecord and teach you everything you need to know to manage complex relationships and queries. Joe Ferris, thoughtbot CTO and querying master, will be guiding us on our journey.

What you should know coming in

This course will focus on advanced usage of built-in ActiveRecord querying methods, as well as how we can break out into custom SQL when we really need to. Our goal is to completely avoid doing data filtering and sorting in plain old Ruby.

Having an understanding of SQL wouldn't hurt. If you need a primer on SQL, check out this Giant Robots post. In addition, here's a nice visual representation of SQL joins that will come in handy.

You should also be familiar with the ActiveRecord, associations, and simple querying methods described below.

Basic ActiveRecord query methods

The following code should look very familiar:

  where(location: location).
  order(name: :asc).
Position.where(active: true).limit(5)
person.positions.where(active: true)

Encapsulating queries in models

You should be familiar with defining class methods or scopes to encapsulate your querying logic:

class Person < ActiveRecord::Base
  def self.alphabetical
    order(name: :asc)

  scope :billable, -> { where(billable: true) }

  has_one :latest_position,
    -> { order(starts_on: :desc) },
    class_name: "Position"

Class methods vs scopes

There isn't much difference between defining class methods and using ActiveRecord's scope API at this point, so it's really a matter of preference. The most important thing is to pick one that you like as a team and stick with it.

Lambdas in associations

Another thing you can do in an association is pass a lambda and use querying methods there, as in the has_one :latest_position example above. This isn't very commonly used, but can be useful for certain situations where you need to eager load associated data in a particular way.

What we'll learn

You should feel great about all of the above. In the rest of this course, we're going to be diving into more interesting things you can:

  • Query objects and their associations in one database hit
  • Write your own custom SQL when you need to
  • Perform calculations on your data and filtering by the results

And, most importantly, how to do all of this in the database -- not in your application with plain old Ruby -- while retaining most of the elegant ActiveRecord DSL that we know and love. This will result in much more efficient applications and maintainable code. Let's get started!