0
0
Ruby on Railsframework~5 mins

Joins and includes in Ruby on Rails

Choose your learning style9 modes available
Introduction

Joins and includes help you get related data from the database efficiently. They make your app faster and avoid repeating queries.

When you want to get records from two tables connected by a relationship.
When you want to load related data in one go to avoid slow multiple queries.
When you want to filter records based on related table conditions.
When you want to show data from related tables in your app views.
When you want to improve performance by reducing database calls.
Syntax
Ruby on Rails
Model.joins(:association)
Model.includes(:association)

joins creates an SQL INNER JOIN and returns records matching the join condition.

includes loads associated records in advance to avoid extra queries (eager loading).

Examples
Gets posts that have comments by joining posts and comments tables.
Ruby on Rails
Post.joins(:comments)
Loads posts and their comments together to avoid extra queries when accessing comments.
Ruby on Rails
Post.includes(:comments)
Gets posts with only approved comments by joining and filtering.
Ruby on Rails
Post.joins(:comments).where(comments: { approved: true })
Loads posts with title 'Hello' and their comments in one go.
Ruby on Rails
Post.includes(:comments).where(title: 'Hello')
Sample Program

This example shows how to use joins to get posts that have comments and includes to load posts with their comments efficiently. It prints post titles from the join and shows how many comments each post has when using includes.

Ruby on Rails
class Post < ApplicationRecord
  has_many :comments
end

class Comment < ApplicationRecord
  belongs_to :post
end

# Get posts with comments using joins
posts_with_comments = Post.joins(:comments).distinct

# Get posts and load comments to avoid extra queries
posts_with_includes = Post.includes(:comments).limit(2)

# Print results
puts "Posts with comments (joins):"
posts_with_comments.each { |p| puts p.title }

puts "\nPosts with comments loaded (includes):"
posts_with_includes.each do |p|
  puts "#{p.title} has #{p.comments.size} comments"
end
OutputSuccess
Important Notes

Use joins when you want to filter or match records based on related tables.

Use includes to avoid the N+1 query problem by loading related data in advance.

joins returns only records with matching associations; includes returns all records and loads associations separately.

Summary

joins connects tables to filter or find matching records.

includes loads related data ahead to speed up access.

Both help your app get related data efficiently and avoid slow database calls.