为什么这个二级预加载不起作用?

Why isn't this second-level eager loading working?

我有三个模型,Subrating、Thing 和 Category。细分 belongs_to 事物和事物 has_many 类别。

我有一个子评级列表,我正在尝试预先加载与每个子评级关联的事物关联的类别。

这是我试过的:


控制器

@subratings = Subrating.all( :include => { :thing => :categories })

查看

<% @subratings.sort_by(&:rating).reverse.each do |subrating| %>
  <%= subrating.thing.categories.sort_by(&:thing_count).second.name %>
<% end %>

但是并没有解决我的n+1问题。我什至不确定数据库是否延迟加载事物或类别或两者,但这是在我的服务器中重复出现数百次的行:

CACHE (0.0ms)  SELECT COUNT(*) FROM "things" INNER JOIN "category_things" ON "things"."id" = "category_things"."thing_id" WHERE "category_things"."category_id" =   [["category_id", 1]]

我做错了什么?


协会

class Subrating < ActiveRecord::Base
  belongs_to :thing
end

class Thing < ActiveRecord::Base
  has_many :category_things
  has_many :categories, :through => :category_things
  has_many :subratings
end

class Category < ActiveRecord::Base
  has_many :category_things
  has_many :things, :through => :category_things
end

class CategoryThing < ActiveRecord::Base
  belongs_to :category
  belongs_to :thing
end

也许您应该尝试在模型 class 上调用包含,例如:

@subratings = Subrating.includes(thing: [:categories])

http://apidock.com/rails/ActiveRecord/QueryMethods/includes

中所述

虽然它也应该按照您尝试的方式工作,因为 .all.find(:all) 的别名,但我建议尝试:

@subratings = Subrating.all( :includes => { :thing => [:categories] })

(请注意,我将 include 更改为 includes 并将对象指向一个数组)

@subratings = Subrating.includes(:thing => :categories)

这也适用于您,并为您提供子字符串 table.

的所有记录