4

I have the following simple where find condition:

Player.where('id NOT IN (?)', @groups.collect {|g| g.player_ids}.flatten)

So this finds all players that are currently not in any groups, right? Well, the problem is that if there are no players in any groups, nothing is shown. The reason for this is the following SQL is generated:

SELECT "players".* FROM "players" WHERE (id NOT IN (NULL))

This seems like a strange default to me, and I've tested it in Rails 3.0.7 and 3.1.0.rc4 with the same result. Now I could create some conditions if @groups.collect {|g| g.player_ids} is empty, but is there a better way to do this?

2 Answers 2

2

You may not like this any better, but...

Player.where('id not in (select id from players where id in (?))', 
    @groups.collect {|g| g.player_ids}.flatten)
Sign up to request clarification or add additional context in comments.

2 Comments

That works the way I wanted, and it will work perfectly since I'm only working on collections smaller than 100. Thanks!
subquery is not so bad if use small collections
0
@groups.collect {|g| g.player_ids}.flatten.join(',')

6 Comments

Unfortunately that don't work with PostgreSQL, it gives the following error: PGError: ERROR: invalid input syntax for integer: ""
what's the SQL generated by this query. BTW, do you handle the case when this id-s collection is empty?
SQL: SELECT "players".* FROM "players" WHERE (id NOT IN ('')). I'm not doing anything to handle the empty collection as I assumed it would default to get all records if the collection was empty.
it's not default. The ruby code just returns the empty collection, then AREL combine the SQL query.
I originally wrote the query in MongoDB and it worked like that there, I guess I just expected it to be a standard. Thanks for your time, Mikhailov.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.