【发布时间】:2015-05-28 20:38:28
【问题描述】:
我有三个模型,Subrating、Thing 和 Category。子分类belongs_to Thing 和Thing has_many Categories。
我有一个 Subratings 列表,我正在尝试快速加载与每个 Subratings 关联的事物相关联的类别。
这是我尝试过的:
控制器
@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" = $1 [["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
【问题讨论】:
标签: mysql ruby-on-rails ruby database associations