使用select,group和Rails进行查询将无法正常工作

时间:2013-06-22 16:06:05

标签: ruby-on-rails ruby-on-rails-3

@violators = User.includes(:violation).select('users.id, violations.id')
  .group('users.id, violations.id').having("COUNT(violations.user_id) >= ?", 5)
  .order("COUNT(violations.user_id) desc")

每个用户has_many违规。通过上面的查询,我可以订购违规次数最多的用户,但我只想查看有5次或更多次违规的用户。当我插入5时,尽管存在超过5次违规的用户,但没有显示任何内容。当我在那里输入1时,所有有违规行为的用户都会出现!

更新:

我无法按照之前的建议订购违规次数最多的用户。也许实际的违规计数存在问题。它不知何故没有抓住它们。虽然当我检查控制台并尝试运行 - user.violation.count时,它会给我准确的计数。

1 个答案:

答案 0 :(得分:6)

您需要在请求中加入joins

@violators = User.joins(:violations).includes(:violations)      
  .group('user_id').having('COUNT(*) >= ?', 5)
  .order('COUNT(*) desc')

我已在我的模型ChampionshipMatch(锦标赛has_many匹配)上对其进行了测试:

Championship.joins(:matches).includes(:matches)
  .group('championship_id').having('count(*) >= ?', 5).order('count(*) DESC').all

SQL请求:

 SQL (0.5ms)  SELECT "championships"."id" AS t0_r0, "championships"."created_at" AS t0_r4, "championships"."updated_at" AS t0_r5, "matches"."id" AS t1_r0, "matches"."championship_id" AS t1_r1, "matches"."created_at" AS t1_r9, "matches"."updated_at" AS t1_r10, "matches"."result" AS t1_r11, "matches"."map_token" AS t1_r12 FROM "championships" INNER JOIN "matches" ON "matches"."championship_id" = "championships"."id" GROUP BY championship_id HAVING count(*) >= 5 ORDER BY count(*) DESC