rails Eager loading

来源:互联网 发布:北京租房软件 编辑:程序博客网 时间:2024/06/05 10:53

     若存在如下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_onend

首先,解决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)


原创粉丝点击