我有三种型号,Subrating,Thing和Category。 Subrating belongs_to Thing,and Thing has_many Categories。
我有一个Subrating列表,我试图加载与每个Subrating关联的Things相关的类别。
这就是我的尝试:
控制器
@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
答案 0 :(得分:1)
也许您应该尝试在Model类上调用includes,如:
@subratings = Subrating.includes(thing: [:categories])
如http://apidock.com/rails/ActiveRecord/QueryMethods/includes
中所述虽然它也应该按照您尝试的方式工作,因为.all
是.find(:all)
的别名,但我会建议尝试:
@subratings = Subrating.all( :includes => { :thing => [:categories] })
(请注意,我将include
更改为includes
,并将事物指向数组)
答案 1 :(得分:0)
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
这对您也有用,并为您提供子串表的所有记录。