2014-12-08 65 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

相關問題