2013-02-10 96 views
0

我使用postgres並希望排除當前在另一個表中的用戶。目前我正在嘗試通過Rails中的ActiveRecord系統來做到這一點。psql不包括基於另一個表的記錄

所以我需要它從我的可用性表中獲取ID,然後將該ID返回到我的用戶表中,如果它們位於可用性表中,則將其刪除。

@availabilities = Availability.where(:event_id => params[:id]).all 
@players = User.where('team_id = ? and id <> ?', current_user[:team_id], @availabilities).all 

此函數返回以下錯誤

PG::Error: ERROR: argument of WHERE must be type boolean, not type record 
LINE 1: SELECT "users".* FROM "users" WHERE (team_id = 1 and id <> ... 
              ^
: SELECT "users".* FROM "users" WHERE (team_id = 1 and id <> 101,102,103) 

改變的代碼如下所述,雖然我做的方式可能仍然不理想

@availabilities = Availability.where(:event_id => params[:id]).all 
@exclude = Availability.where(:event_id => params[:id]).select(:user_id).pluck(:user_id) 
if @exclude.count > 0 
    @players = User.where('team_id = ? and id NOT IN (?)', current_user[:team_id], @exclude).all 
else 
    @players = User.where('team_id =?', current_user[:team_id]) 
+0

如果它們排除在外你不想再次訪問數據庫,你可以這樣做@exclude = @ availabilites.map {| a |改爲a.user_id}。 – 2013-02-10 13:40:17

回答

4

你可以做這樣的事情:

@availabilities = Availability.where(event_id: params[:id]).pluck(:id) 
@players = User.where(team_id: current_user[:team_id]) 
@players = @players.where('id NOT IN (?)', @availabilities) unless @availabilities.empty? 

使用pluck()將返回一組ID,那麼你可以通過使用NOT IN (?)

+0

唯一的問題,我有,如果它的空 – 2013-02-10 06:07:31

+0

你的意思是如果id數組是空的?我已經更新了我的答案。 – 2013-02-10 08:07:10

1

嘗試:

id not in 

The ((team_id = 1和id <> 101),102,103)。因此你看到的錯誤。

使用它作爲:

User.where('team_id = ? and id not in (?)', current_user[:team_id], @availabilities).all 
相關問題