Aller au contenu

Query Inside Loop (ARCH6064)

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

Key ruby.orm.query-inside-loop · Severity warning · Category orm

Any DB query inside a loop body (broader than relation N+1: includes ad-hoc find, aggregates, repository calls) produces one round-trip per iteration.

ids.each do |id|
user = User.find(id) # a separate query per iteration
process(user)
end
users = User.where(id: ids) # all in one query
users.each { |user| process(user) }

Hoist queries out of the loop so the needed records are fetched in a single query beforehand.