Skip to content

N+1 Query (ARCH6050)

Key ruby.orm.n-plus-one-query · Severity warning · Category orm

Fetching a related record with a separate query for each element while iterating over a collection causes the N+1 query problem. This is the classic ORM performance killer.

posts = Post.all
posts.each do |post|
puts post.author.name # a separate SELECT per iteration
end
posts = Post.includes(:author)
posts.each do |post|
puts post.author.name # author loaded in one go
end

Eager-load related data with includes before the loop; do not issue a new query per iteration.