İçeriğe geç

N+1 Sorgusu (ARCH6050)

Anahtar ruby.orm.n-plus-one-query · Önem warning · Kategori orm

Bir koleksiyon üzerinde dönerken her eleman için ilişkili kaydı ayrı bir sorguyla çekmek, N+1 sorgu problemine yol açar. Bu, ORM performansını öldüren klasik hatadır.

posts = Post.all
posts.each do |post|
puts post.author.name # her tur için ayrı SELECT
end
posts = Post.includes(:author)
posts.each do |post|
puts post.author.name # author tek seferde yüklendi
end

İlişkili veriyi döngüden önce includes ile eager-load edin; her iterasyonda yeni sorgu üretmeyin.