📖 Scenario: You are building a simple blog application where each Post has many Comments. You want to fetch posts along with their comments efficiently.
🎯 Goal: Learn how to use joins and includes in Rails ActiveRecord to query posts and their comments.
📋 What You'll Learn
Create a Post model with a title attribute
Create a Comment model with a content attribute and a post_id foreign key
Use joins to find posts that have comments
Use includes to load posts with their comments to avoid N+1 queries
💡 Why This Matters
🌍 Real World
Fetching related data efficiently is common in web apps to improve speed and reduce database load.
💼 Career
Understanding joins and includes is essential for Rails developers to write performant database queries and avoid common pitfalls like N+1 queries.
Progress0 / 4 steps
1
Create Post and Comment models with sample data
Create a Post model with a title attribute and a Comment model with a content attribute and a post_id foreign key. Then create two posts: one with title 'First Post' and another with title 'Second Post'. Create two comments for the first post with contents 'Great post!' and 'Thanks for sharing.'.
Ruby on Rails
Hint
Define the models with associations and create posts and comments exactly as described.
2
Set a variable to hold posts with comments using joins
Create a variable called posts_with_comments and assign it the result of using joins(:comments) on the Post model to find posts that have at least one comment.
Ruby on Rails
Hint
Use Post.joins(:comments).distinct to get posts that have comments.
3
Use includes to load posts with comments to avoid N+1 queries
Create a variable called posts_with_includes and assign it the result of using includes(:comments) on the Post model to load posts with their comments efficiently.
Ruby on Rails
Hint
Use Post.includes(:comments) to load posts with their comments efficiently.
4
Access comments from posts_with_includes to complete the example
Add a loop that iterates over posts_with_includes and for each post, access its comments association to demonstrate that comments are loaded without extra queries.
Ruby on Rails
Hint
Use a loop with posts_with_includes.each do |post| ... end and call post.comments.load inside to access comments.
Practice
(1/5)
1. What is the main purpose of using joins in Rails ActiveRecord queries?
easy
A. To update multiple tables at once
B. To preload associated records to avoid extra database queries
C. To combine tables and filter records based on matching columns
D. To delete records from multiple tables
Solution
Step 1: Understand what joins does
joins connects tables in a query to filter or find records that match conditions across those tables.
Step 2: Compare with includes
includes is used to preload associated data to reduce queries, not for filtering.
Final Answer:
To combine tables and filter records based on matching columns -> Option C
Quick Check:
joins = combine tables for filtering [OK]
Hint: Remember: joins filters by matching tables, includes preloads data [OK]
Common Mistakes:
Confusing joins with includes
Thinking joins preload data
Assuming joins update or delete records
2. Which of the following is the correct syntax to use includes to preload the comments association on a Post model?
easy
A. Post.includes('comments').where(published: true)
B. Post.includes(:comments).where(published: true)
C. Post.include(:comments).where(published: true)
D. Post.joins(:comments).includes.where(published: true)
Solution
Step 1: Check the correct method name and argument type
The method is includes (plural), and it accepts a symbol like :comments.
Step 2: Validate the chaining and syntax
Post.includes(:comments).where(published: true) uses Post.includes(:comments).where(published: true), which is correct syntax to preload comments and filter posts.
Final Answer:
Post.includes(:comments).where(published: true) -> Option B
Quick Check:
Correct method and symbol argument = Post.includes(:comments).where(published: true) [OK]
Hint: Use plural includes with symbol for associations [OK]
Common Mistakes:
Using singular include instead of includes
Passing association as string instead of symbol
Chaining includes incorrectly
3. Given these models: Author has_many :books and Book belongs_to :author, what will this query return?
A. No error; the query is valid and will work as expected
B. The where clause should reference authors instead of comments
C. Using both joins and includes together causes a syntax error
D. The includes should come before joins to avoid errors
Solution
Step 1: Check if using joins and includes together is allowed
Rails allows chaining joins and includes to combine filtering and eager loading.
Step 2: Verify the where clause references a valid table
The where filters on comments which is joined, so it's valid.
Final Answer:
No error; the query is valid and will work as expected -> Option A
Quick Check:
joins + includes + where on joined table = valid [OK]
Hint: joins and includes can be chained; where must match joined tables [OK]
Common Mistakes:
Thinking joins and includes can't be combined
Confusing which table to filter in where
Assuming order of joins/includes causes errors
5. You want to fetch all Order records with their associated Customer and OrderItems, but only include orders where the customer is active and at least one order item is in stock. Which query correctly uses joins and includes to achieve this efficiently?