Performance: Eager loading (N+1 prevention)
This concept affects database query efficiency and page load speed by reducing the number of queries needed to fetch related data.
posts = Post.includes(:author).all posts.each do |post| puts post.author.name end
posts = Post.all posts.each do |post| puts post.author.name end
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| N+1 queries (lazy loading) | Normal | Multiple due to delayed data | Higher due to slower data | [X] Bad |
| Eager loading with includes | Normal | Single or fewer | Lower due to faster data | [OK] Good |
includes in Rails when querying data?includesincludes method tells Rails to load all associated records in one or few queries, preventing many extra queries.comments association for Post records?includes to eager load associations simply and efficiently.Post.includes(:comments) is the correct syntax to load posts with their comments in fewer queries.posts = Post.all posts.each do |post| puts post.comments.count end
Post.all loads all posts in 1 query. Then inside the loop, post.comments.count triggers a query per post to count comments.posts = Post.includes(:comments).where(published: true) posts.each do |post| puts post.comments.count end
count works on associationspost.comments.count runs a SQL COUNT query for each post, ignoring preloaded records.includes loads all comments, but count asks database for count separately, causing N+1 queries.count on association triggers a separate query despite eager loading -> Option DAuthor.includes(books: :reviews) loads authors, their books, and reviews in minimal queries.Pass the test and this pattern moves unknown