Aller au contenu

Orm N Plus One Query (ARCH6079)

Ce contenu n’est pas encore disponible dans votre langue.

Key ruby.performance.orm-n-plus-one · Severity error · Category performance

Looping over a query result and accessing each item’s relationship fires a separate query per record (N+1). Eager-load the relationship with includes.

def author_names(posts)
Post.where(published: true).map do |post|
post.author.name
end
end
def author_names(posts)
Post.where(published: true).includes(:author).map do |post|
post.author.name
end
end

Eager-load related records with includes/preload when you access them inside a loop.