Joins and includes help you get related data from the database efficiently. They make your app faster and avoid repeating queries.
Joins and includes in 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).
Post.joins(:comments)
Post.includes(:comments)
Post.joins(:comments).where(comments: { approved: true })Post.includes(:comments).where(title: 'Hello')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.
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
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.
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.