author avatar

nitturu.baba

Tue Oct 29 2024

To avoid N+1 queries in Rails, you can use the .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.



orders = Order.all 
orders.each do |order| 
  puts order.items # Each order triggers a separate query for items
end


By using .includes, Rails will fetch all associated items in a single additional query:



orders = Order.includes(:items)
orders.each do |order|
  puts order.items # No extra query is triggered here
end


This approach loads Order records in one query and then fetches all associated items in a second query, avoiding the N+1 issue.

#CU6U0R822