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))
以下用于导轨3
Product.where('id NOT IN (?)', [2,3,4,5,6])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.