我是RoR的新手。请帮我: 我有两个模型:
class User < ActiveRecord::Base
belongs_to :game
end
和
class Game < ActiveRecord::Base
has_many :users, :foreign_key => "game_id"
end
游戏对象有很多用户。我需要找到所有Game对象,其中users.count == 1.请帮忙。
答案 0 :(得分:1)
MrYoshiji的答案很接近,但您需要使用where
和group
,而不是尝试使用having
。
例如:
Game.joins(:users).group("users.game_id").having("count(users.game_id) = 1")
这将产生以下查询:
SELECT games.* FROM "games" INNER JOIN "users" ON "users"."game_id" = "games"."id" GROUP BY users.game_id HAVING count(users.game_id) = 1
答案 1 :(得分:0)
有点长但这对我有用:
Game.joins(:users).where("(select count(users.game_id) from users users2 where users2.game_id = games.id) = 1")
您可以使用includes()
或joins()
,具体取决于您的目标。