我首先有这个:
@shots = @team.shots.order_by_recent.limit(5)
然后我想在其他方法中使用@shots
:
made = @shots.where(made: true).count
=> 5 (should be 2)
missed = @shots.where(made: true).count
=> 5 (should be 3)
生成的查询:
SELECT COUNT(DISTINCT count_column)
FROM (SELECT "shots"."id" AS count_column FROM "shots"
LEFT OUTER JOIN "games" ON "games"."id" = "shots"."game_id"
WHERE "shots"."team_id" = $1 AND "shots"."shot_area" = $2
AND "shots"."shot_range" = $3 AND "shots"."made" = 'f' LIMIT 5)
subquery_for_count [["team_id", 3], ["shot_area", "Left Side Center(LC)"], ["shot_range", "24+ ft."]]
我注意到LIMIT
最后应用于整个查询。我想要做的是首先将限制应用于@team.shots.order_by_recent
,然后对其进行额外的查询。
换句话说: 我想将查询分成两个单独的查询。第一个查询获得5条记录:@ team.shots.order_by_recent.limit(5),第二条查询从第一个查询中选择。现在,似乎Rails会自动将这两个查询合并为一个。