Challenge 3: Fix an N+1 Query — Solution Original (N+1 problem): Author.all.each { |author| puts author.books.count } Total queries for 20 authors: 21 (1 query for Author.all, plus 1 additional query per author inside the loop for author.books.count — 1 + 20 = 21 queries total.) Fixed: Author.includes(:books).each { |author| puts author.books.count } New total query count: 2 (1 query for the authors themselves, plus 1 additional query that eager-loads every author's books all at once, run BEFORE the loop starts — regardless of how many authors exist, the total stays at 2.) =begin Notes: - The original version's cost scales directly with the number of authors -- 200 authors would mean 201 queries, not just 21. This is exactly why the N+1 problem gets worse (and more noticeable) as real data grows, even though it looks harmless with a small test dataset. - .includes(:books) is the one-word fix: it tells Active Record to eager-load the association ahead of time in a single extra query, instead of lazily querying for each author's books individually the first time author.books is actually accessed inside the loop. - The fixed version's query count stays flat at 2 no matter how many authors exist, which is the actual goal -- not just "fewer queries" but a query count that doesn't grow with the size of the dataset. =end