Ruby on Rails ActiveRecord Joins Explained

Learn how ActiveRecord joins work in Ruby on Rails with practical examples of inner joins, left joins, association filters, includes, and performance tips.

By Anderson Alvarez Vásquez · 2026-07-05

  • programming
  • ruby
  • tutorials
  • Databases
  • SQL

ActiveRecord Joins: A Practical Guide for Ruby on Rails ActiveRecord joins are one of the most important tools for writing efficient database queries in Ruby on Rails. They allow you to query records based on relationships between tables without loading unnecessary data into memory. Example Models Imagine a simple blog application: ruby class Post < ApplicationRecord belongs to :author has many :comments end class Author < ApplicationRecord has many :posts end class Comment < ApplicationRecord belongs to :post end With these relationships, Rails can generate SQL joins using ActiveRecord methods. Basic Inner Join The joins method creates an SQL INNER JOIN . ruby Post.joins :author This returns posts that have an associated author. The generated SQL is similar to: sql SELECT posts. FROM posts INNER JOIN authors ON authors.id = posts.author id; An inner join only returns records where the relationship exists on both sides. Filtering by Associated Records Joins become more useful when combined with where . ruby Post.joins :author .where authors: { active: true } This returns only posts written by active authors. ruby Post.joins :comments .where comments: { approved: true } This returns posts that have at least one approved comment. Left Outer Join Sometimes you need records even if the association does not exist. In that case, use left joins or left outer joins . ruby Post.left joins :comments This returns all posts, including posts without comments. A common use case is finding records without associated data: ruby Post.left joins :comments .where comments: { id: nil } This returns posts with no comments. joins vs includes A common mistake is confusing joins with includes . Use joins when you need to filter or sort using associated tables: ruby Post.joins :author .where...