我们应该尽量减少从数据库取数据的次数:
Tasks
- <% @tasks.each do |task| %>
-
- <%= link_to task.name, task %> in <%= task.project.name %>
- <% end %>
- The view code for the Tasks index page.
在这段代码中,每一个task都会执行一次数据库操作,在rails2.*中,具有cache的功能,如果两次的sql命令相同,则不会发起数据库操作,而是在cache中取出数据。而在rails1.*中,没有cache,每次都要发起数据库查询操作。
eager loading可以帮我们解决这个问题:
在controller中,
@tasks = Task.find(:all, :include => :project)
(因为在task model中,我们有belongs_to :project)
我们甚至还可以include more than one association:
belongs_to :project
has_many :comments
@tasks = Task.find(:all, :include => [:project, :comments])
更复杂的,如果在comment对象中,
belongs_to :task
belongs_to :user
那么还可以:
@tasks = Task.find(:all, :include => [:project, :comments => :user])
这样不但把comments取出来了,而且把comment所属的user也取出来了!
阅读(498) | 评论(0) | 转发(0) |