Bird
Raised Fist0
Ruby on Railsframework~10 mins

Eager loading (N+1 prevention) in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Eager loading (N+1 prevention)
Query Parent Records
↓
Check for Associated Records
↓
Without Eager Loading
↓
For each parent, query associated
↓
Many queries (N+1 problem)
↓
Slow performance
Shows how fetching associated records separately causes many queries (N+1 problem), while eager loading fetches all at once for speed.
Execution Sample
Ruby on Rails
posts = Post.all
posts.each do |post|
  puts post.comments.count
end
This code fetches all posts, then for each post fetches its comments count, causing many queries (N+1 problem).
Execution Table
StepActionQuery ExecutedNumber of Queries So FarResult
1Fetch all postsSELECT * FROM posts;1Posts loaded
2For post 1, fetch comments countSELECT COUNT(*) FROM comments WHERE post_id = 1;2Comments count for post 1
3For post 2, fetch comments countSELECT COUNT(*) FROM comments WHERE post_id = 2;3Comments count for post 2
4For post 3, fetch comments countSELECT COUNT(*) FROM comments WHERE post_id = 3;4Comments count for post 3
5End loopNo query4All posts processed
💡 Loop ends after all posts processed; total queries = 1 (posts) + N (comments per post)
Variable Tracker
VariableStartAfter 1After 2After 3Final
postsnil[post1, post2, post3][post1, post2, post3][post1, post2, post3][post1, post2, post3]
postnilpost1post2post3nil
comments_countnilcount for post1count for post2count for post3nil
Key Moments - 2 Insights
Why does the code run one query per post to get comments count?
Because inside the loop, calling post.comments.count triggers a separate query each time, as shown in execution_table rows 2-4.
How does eager loading fix the N+1 problem?
Eager loading fetches all comments for all posts in one query before the loop, avoiding multiple queries during iteration.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, how many queries run after fetching 3 posts and their comments counts without eager loading?
A1
B3
C4
D6
💡 Hint
Check the 'Number of Queries So Far' column in the execution_table after step 4.
If we add eager loading with Post.includes(:comments), how many queries will run for 3 posts and their comments?
A1
B2
C3
D4
💡 Hint
Eager loading runs one query for posts and one for comments, see key_moments explanation.
In variable_tracker, what is the value of 'post' after step 3?
Apost3
Bpost2
Cpost1
Dnil
💡 Hint
Look at the 'post' row and the 'After 3' column in variable_tracker.
Concept Snapshot
Eager loading prevents N+1 queries by fetching associated records in advance.
Without it, each parent record triggers a query for its children.
Use Post.includes(:comments) to load posts and comments in two queries.
This improves performance by reducing database hits.
Always eager load when accessing associations in loops.
Full Transcript
This visual execution shows how fetching posts and their comments without eager loading causes multiple queries, one per post, known as the N+1 problem. The code first runs one query to get all posts, then inside a loop, each post triggers a separate query to count its comments. This leads to slow performance. Eager loading solves this by running one query for posts and one for all comments, reducing queries drastically. The variable tracker shows how variables change during execution. The key moments clarify why queries multiply and how eager loading fixes it. The quizzes test understanding of query counts and variable states.

Practice

(1/5)
1. What is the main purpose of using includes in Rails when querying data?
easy
A. To load associated records in fewer database queries and avoid N+1 problems
B. To delete associated records automatically
C. To sort records alphabetically
D. To create new associated records

Solution

  1. Step 1: Understand N+1 query problem

    When loading records with associations, Rails may run one query for the main records and one query per associated record, causing many queries.
  2. Step 2: Role of includes

    The includes method tells Rails to load all associated records in one or few queries, preventing many extra queries.
  3. Final Answer:

    To load associated records in fewer database queries and avoid N+1 problems -> Option A
  4. Quick Check:

    Eager loading = fewer queries = better speed [OK]
Hint: Remember: includes = fewer queries, faster loading [OK]
Common Mistakes:
  • Thinking includes deletes records
  • Confusing includes with sorting
  • Assuming includes creates new records
2. Which of the following is the correct syntax to eager load the comments association for Post records?
easy
A. Post.eager_load(:comments)
B. Post.load_comments
C. Post.includes(:comments)
D. Post.with_comments

Solution

  1. Step 1: Identify the standard eager loading method

    Rails uses includes to eager load associations simply and efficiently.
  2. Step 2: Check syntax correctness

    Post.includes(:comments) is the correct syntax to load posts with their comments in fewer queries.
  3. Final Answer:

    Post.includes(:comments) -> Option C
  4. Quick Check:

    Correct eager loading syntax = includes [OK]
Hint: Use includes(:association) to eager load in Rails [OK]
Common Mistakes:
  • Using non-existent methods like load_comments
  • Confusing eager_load with includes (different behavior)
  • Using with_comments which is not a Rails method
3. Given the code below, what will be the total number of database queries executed?
posts = Post.all
posts.each do |post|
  puts post.comments.count
end
medium
A. 1 query
B. N+1 queries, where N is the number of posts
C. 2 queries
D. No queries

Solution

  1. Step 1: Analyze the code without eager loading

    Post.all loads all posts in 1 query. Then inside the loop, post.comments.count triggers a query per post to count comments.
  2. Step 2: Calculate total queries

    1 query for posts + N queries for comments count = N+1 queries total.
  3. Final Answer:

    N+1 queries, where N is the number of posts -> Option B
  4. Quick Check:

    Without includes, each association call triggers a query [OK]
Hint: Looping over associations without includes causes N+1 queries [OK]
Common Mistakes:
  • Assuming only 1 query runs
  • Thinking count does not query database
  • Confusing eager_load with includes
4. You wrote this code to eager load comments but still see many queries:
posts = Post.includes(:comments).where(published: true)
posts.each do |post|
  puts post.comments.count
end

What is the likely cause of the N+1 queries still happening?
medium
A. Eager loading only works with all method
B. The where clause disables eager loading
C. You must use joins instead of includes
D. Using count on association triggers a separate query despite eager loading

Solution

  1. Step 1: Understand how count works on associations

    Calling post.comments.count runs a SQL COUNT query for each post, ignoring preloaded records.
  2. Step 2: Why eager loading doesn't prevent count queries

    includes loads all comments, but count asks database for count separately, causing N+1 queries.
  3. Final Answer:

    Using count on association triggers a separate query despite eager loading -> Option D
  4. Quick Check:

    count triggers query even with includes [OK]
Hint: Use size or length on loaded associations to avoid extra queries [OK]
Common Mistakes:
  • Thinking where disables includes
  • Believing joins always eager load
  • Assuming eager loading needs all method
5. You want to display a list of authors with their books and each book's reviews efficiently. Which is the best way to eager load these nested associations in Rails?
hard
A. Author.includes(books: :reviews)
B. Author.includes(:books, :reviews)
C. Author.joins(:books).joins(:reviews)
D. Author.eager_load(:books, :reviews)

Solution

  1. Step 1: Understand nested associations eager loading

    To load authors with books and each book's reviews, nested includes syntax is needed.
  2. Step 2: Choose correct nested includes syntax

    Author.includes(books: :reviews) loads authors, their books, and reviews in minimal queries.
  3. Step 3: Why other options are incorrect

    Author.includes(:books, :reviews) tries to load reviews directly on authors (wrong association). Author.joins(:books).joins(:reviews) uses joins which may not eager load. Author.eager_load(:books, :reviews) eager_load loads with joins but is less flexible.
  4. Final Answer:

    Author.includes(books: :reviews) -> Option A
  5. Quick Check:

    Nested includes = includes(parent: :child) [OK]
Hint: Use nested hash in includes for nested associations [OK]
Common Mistakes:
  • Trying to include unrelated associations directly
  • Using joins instead of includes for eager loading
  • Misunderstanding nested includes syntax
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard