Query Inside Loop (ARCH6064)
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.
Incorrect
Section titled “Incorrect”ids.each do |id| user = User.find(id) # a separate query per iteration process(user)endCorrect
Section titled “Correct”users = User.where(id: ids) # all in one queryusers.each { |user| process(user) }Hoist queries out of the loop so the needed records are fetched in a single query beforehand.