如何从较少的查询中加载此内容?
当前代码; 控制器;
@players = @season.players.includes(:stats)
视图;
<% @players.each do |player| %>
<%= player.stats.where(season: @season).each do |stat| %>
<% end %>
<% end %>
查询;
Season Load (0.1ms) SELECT "seasons".* FROM "seasons" WHERE "seasons"."id" = ? LIMIT 1 [["id", 1]]
Player Load (0.2ms) SELECT "players".* FROM "players" INNER JOIN "player_seasons" ON "players"."id" = "player_seasons"."player_id" WHERE "player_seasons"."season_id" = ? [["season_id", 1]]
Stat Load (0.3ms) SELECT "stats".* FROM "stats" WHERE "stats"."player_id" IN (1, 2)
Stat Load (0.1ms) SELECT "stats".* FROM "stats" WHERE "stats"."player_id" = ? AND "stats"."season_id" = 1 [["player_id", 1]]
Stat Load (0.1ms) SELECT "stats".* FROM "stats" WHERE "stats"."player_id" = ? AND "stats"."season_id" = 1 [["player_id", 2]]
Rendered seasons/show.html.erb within layouts/application (5.4ms)
谢谢。
答案 0 :(得分:0)
您是否尝试过preload
或eager_load
而不是includes
?
有很多关于各种联接的好信息可以在这里找到:http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html