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!!!
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))
Use following for rails 3
Product.where('id NOT IN (?)', [2,3,4,5,6])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With