Lazy Load In Loop (ARCH6059)
Ce contenu n’est pas encore disponible dans votre langue.
Key ruby.orm.lazy-load-in-loop · Severity warning · Category orm
Accessing a lazily-loaded relation on each element of an iterated collection triggers N+1 at runtime when eager loading was omitted. The relation must be loaded before the loop.
Incorrect
Section titled “Incorrect”orders.each do |order| total += order.customer.discount # lazy-loads customer each iterationendCorrect
Section titled “Correct”orders = orders.includes(:customer)orders.each do |order| total += order.customer.discountendPreload the relations accessed in the loop with includes to prevent lazy-load triggering.