0
0
Ruby on Railsframework~5 mins

Eager loading (N+1 prevention) in Ruby on Rails

Choose your learning style9 modes available
Introduction

Eager loading helps your app get related data all at once. This stops slowdowns caused by asking the database many times.

When you want to show a list of posts with their authors without extra database calls.
When loading comments for many articles and want to avoid loading each comment separately.
When displaying products with their categories in one page efficiently.
When you notice your app is slow because it queries the database repeatedly for related data.
Syntax
Ruby on Rails
Model.includes(:association)

Use includes with the name of the related data you want to load.

This tells Rails to load the main data and its related data in fewer queries.

Examples
Loads posts and their authors together to avoid extra queries when accessing authors.
Ruby on Rails
Post.includes(:author)
Loads articles and all their comments in one go.
Ruby on Rails
Article.includes(:comments)
Loads products with both their categories and suppliers efficiently.
Ruby on Rails
Product.includes(:category, :supplier)
Sample Program

This controller loads all posts and their authors together. The view then shows each post's title and author name without extra database queries.

Ruby on Rails
class PostsController < ApplicationController
  def index
    @posts = Post.includes(:author).all
  end
end

# In the view (index.html.erb):
# <% @posts.each do |post| %>
#   <p><strong><%= post.title %></strong> by <%= post.author.name %></p>
# <% end %>
OutputSuccess
Important Notes

Without eager loading, accessing post.author for each post causes a new database query.

Eager loading reduces database calls, making your app faster and more efficient.

Use Rails console and logs to see how many queries run with and without includes.

Summary

Eager loading loads related data in fewer queries.

Use includes to prevent the N+1 query problem.

This makes your app faster and smoother for users.