2013-02-11 49 views
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.請幫助。

回答

0

有點長,但這個工作對我來說:

Game.joins(:users).where("(select count(users.game_id) from users users2 where users2.game_id = games.id) = 1") 

您可以使用取決於你想要做什麼includes()joins()

+0

謝謝。它'有用也 – mahmud 2013-02-11 23:08:22

1

MrYoshiji的回答很接近,但不要試圖使用where,您需要使用grouphaving

例如:

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

謝謝。它的工作非常棒! – mahmud 2013-02-11 23:00:34