2014-12-08 66 views
0

我有一个玩家模型和匹配模型。每个比赛有一个赢家和一个输赢球员 loser_id。从一个表中获取不在第二个表中的任一列的所有记录

如何获得所有从未参加过比赛的球员?

I.e.获取所有玩家ID,既不在winner_id也不在loser_id列。

我使用Rails 4

Players 
------------- 
id  
1 
2 
3 
4 
5 
6 
7 

Matches 
------------- 
winner_id  loser_id 
1    2 
1    3 
1    4 

所以结果应该是球员5,6,和7

回答

1

Player.where.not(ID:Match.pluck(:winner_id,:loser_id).flatten.uniq)

0

有可能也有一些更好的办法。但你可以做到这样也:

ids = Matche.select(:winner_id).distinct.map{|match| match.winner_id} + Matche.select(:loser_id).distinct.map{|match| match.loser_id} 
@players = Player.where.not(id: ids) 
+0

'Match.select(:winner_id) .distinct.to_a' returns'[#,#],...'。 所以这个答案不起作用 – 2014-12-08 07:28:34

+0

我已经在我的答案中作出了改变,这将对你有用 – 2014-12-08 07:56:58

相关问题