- Published
- Author
- Nitturu BabaSystem Analyst
To avoid N+1 queries in Rails, you can use the
Suppose you have two models:
By using
This approach loads
#CU6U0R822
.includes method to eager-load associated records, which reduces the number of database calls.Suppose you have two models:
Order and Item, where an Order has many Items. Without eager-loading, querying each order’s items individually would lead to N+1 queries.Code
orders = Order.all
orders.each do |order|
puts order.items # Each order triggers a separate query for items
endBy using
.includes, Rails will fetch all associated items in a single additional query:Code
orders = Order.includes(:items)
orders.each do |order|
puts order.items # No extra query is triggered here
endThis approach loads
Order records in one query and then fetches all associated items in a second query, avoiding the N+1 issue.#CU6U0R822