G0574's Archiver

弯月圆刀 发表于 2008-7-25 14:31

Eager loading of associations

如果你有100条帖子,每条帖子都有一个user_id属性,这个user_id的名字在users表中。这个时候,如果你首先找到100条帖子,然后根据每个帖子的user_id去查找user_name,那么就会出现可怕的1+N问题,为了显示100条带有作者名字的帖子,必须进行101次数据库查询。通过eager loading,101次可以减少到2次。[code]  class Post < ActiveRecord::Base
    belongs_to :author
    has_many   :comments
  end
[/code][code]  for post in Post.all
    puts "Post:            " + post.title
    puts "Written by:      " + post.author.name
    puts "Last comment on: " + post.comments.first.created_on
  end
[/code]上面的代码会产生201次数据库查询。

通过下面的方式:[code]for post in Post.find(:all, :include => :author)
[/code]减少到102次。[code]for post in Post.find(:all, :include => [ :author, :comments ])
减少到3次。


[/code]

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.