我有两个模型: aPerson
有很多Blurb(s)
.
在控制器中,我正在获取所有人并急切地加载简介:
@people = Person.includes(:blurbs).all.sort { |x, y| y.updated_at <=> x.updated_at }
然后在视图中我遍历@people
并显示他们各自的简介计数:
<% @people.each do |person| %>
<%= person.blurbs.count %>
<% end %>
Rails 的记录器显示确实加载了所有简介:
Blurb Load (0.5ms) SELECT "blurbs".* FROM "blurbs" WHERE "blurbs"."person_id" IN \
(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, \
21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 27, 48, 49, 50)
但随后它在迭代而不是从缓存中获取时再次加载它们:
(0.4ms) SELECT COUNT(*) FROM "blurbs" WHERE "blurbs"."person_id" = $1 [["person_id", 27]]
(0.3ms) SELECT COUNT(*) FROM "blurbs" WHERE "blurbs"."person_id" = $1 [["person_id", 50]]
(0.3ms) SELECT COUNT(*) FROM "blurbs" WHERE "blurbs"."person_id" = $1 [["person_id", 49]]
为了减少 SQL 查询,我缺少什么来使用急切加载的简介?