2013-02-11 36 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