我剛剛接觸到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.請幫助。
我剛剛接觸到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.請幫助。
有點長,但這個工作對我來說:
Game.joins(:users).where("(select count(users.game_id) from users users2 where users2.game_id = games.id) = 1")
您可以使用取決於你想要做什麼includes()
或joins()
。
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
謝謝。它的工作非常棒! – mahmud 2013-02-11 23:00:34
謝謝。它'有用也 – mahmud 2013-02-11 23:08:22