Search code examples
ruby-on-railsormrails-activerecordrails-postgresql

psql excluding records base on another table


i am using postgres and wishing to exclude users that are currently in one table from another. at present i am trying do this via the ActiveRecord system within Rails.

So i need it to get the ids from my Availability table, then return that id into my User table to remove them if they are in the Availability table.

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

this is returning the following error

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)

changed code as mentioned below, though the way i am doing it is still probably not ideal

@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])

Solution

  • You could do something like this:

    @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?
    

    Using pluck() will return an array of IDs, then you can exclude them by using NOT IN (?)