20

ActiveRecord has a very neat syntax for querying records where a column is equal to any value in a given array:

For a simple example, let's say you have 10 products with ids 1,2,3,4,5,6,7,8,9,10.

Product.where(id: [2,3,4,5,6])

will return products 2,3,4,5 and 6.

Is there an ActiveRecord equivalent for querying products where the column does not equal any value in an array?

Something like:

Product.where('id != ?', [2,3,4,5,6])

except that it actually works...

And when you pass it [2,3,4,5,6] in this case, it will return products 1,7,8,9 and 10.

EDIT

I need a Rails 3 solution!!!

2 Answers 2

28

You can negate any where clause with where.not in Rails 4:

Product.where.not(id: [2, 3, 4, 5, 6])

In Rails 3 you can leverage ARel:

Product.where(Product.arel_table[:id].not_in([2, 3, 4, 5, 6]))

The generated SQL in both cases is

SELECT "products".* FROM "products" WHERE ("products"."id" NOT IN (2, 3, 4, 5, 6))
Sign up to request clarification or add additional context in comments.

2 Comments

That is introduced in Rails 4 right? I am still (reluctantly) using Rails 3! Can you tell me what SQL this query generates?
You can see what sql is generated by calling to_sql on an ActiveRecord relation object. See my edit.
7

Use following for rails 3

Product.where('id NOT IN (?)', [2,3,4,5,6])

Comments

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.