若存在如下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)
解决Rails应用中N+1查询问题的Eager Loading技巧
本文将详细解释如何在Rails应用中遇到的N+1查询问题,通过使用Eager Loading技术来优化数据加载效率。包括解决author获取问题、comments加载及带条件的eager loading等方法。
923

被折叠的 条评论
为什么被折叠?



