诗歌rails之Rails eager loading
看这个页面代码:
上面的代码对每个task对象,取得project的name属性并显示,看看log:
由于ActiveRecord默认是延迟加载的,这样对每个task对象去取project对象时又会查询一次数据库
对于这种情况,我们使用eager loading就比较合适了:
:include指定我们将project属性一起查询出来,我们再看看log:
- <% for task in @tasks %>
- <%= link_to task.name, task_path(task) %> in <%= task.project.name %>
- <% end %>
上面的代码对每个task对象,取得project的name属性并显示,看看log:
- Project Lood (0.000131) SELECT * FROM projects WHERE (projects.id = 330)
- Project Lood (0.000156) SELECT * FROM projects WHERE (projects.id = 330)
- Project Lood (0.000136) SELECT * FROM projects WHERE (projects.id = 330)
- Project Lood (0.000138) SELECT * FROM projects WHERE (projects.id = 330)
- Project Lood (0.000133) SELECT * FROM projects WHERE (projects.id = 330)
- Project Lood (0.000128) SELECT * FROM projects WHERE (projects.id = 330)
- ...
- Completed in 0.14792 (6 reqs/sec) | ...
由于ActiveRecord默认是延迟加载的,这样对每个task对象去取project对象时又会查询一次数据库
对于这种情况,我们使用eager loading就比较合适了:
- class TasksController < ApplicationController
- def index
- @tasks = Task.find(:all, :include => :project)
- end
- end
:include指定我们将project属性一起查询出来,我们再看看log:
- Task Lood Including Associations (0.000681) SELECT tasks.'id' AS t0_r0, tasks.'name' AS t0_r1, tasks.'project_id' AS
- t0_r2, projects.'id' AS t1_r0, projects.'name' AS t1_r1 FROM tasks LEFT OUTER JOIN projects ON projects.id = tasks.pro
- ject_id
- ...
- Completed in 0.03464 (28 reqs/sec) | ...
莫愁前路无知己,天下无人不识君。