Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord: Query where column NOT in array

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!!!

like image 581
Marco Prins Avatar asked Oct 16 '14 08:10

Marco Prins


Video Answer


2 Answers

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))
like image 163
Patrick Oscity Avatar answered Oct 17 '22 23:10

Patrick Oscity


Use following for rails 3

Product.where('id NOT IN (?)', [2,3,4,5,6])
like image 31
Esha Avatar answered Oct 17 '22 23:10

Esha