若存在如下Post model:
使用下面的循環加載數據時產生了N+1查詢問題:
Post.all.each do |post|
puts "Post: " + post.title
puts "Written by: " + post.author.name
puts "Last comment on: " + post.comments.first.created_on
end
首先,解決author獲取問題:
Post.includes(:author).each do |post|
然後解決comments加載:
Post.includes(:author, :comments).each do |post|
帶條件的eager loading:
Post.includes([:author, :comments]).where(['comments.approved = ?', true]).all
多態關係的eager laoding
Address.includes(:addressable)