How to simulate a NOT IN SQL condition in the following case
I'm using Ruby on Rails 2.3.8 and I would like to get all the @products
that haven't been already added to the listed_products
array.
For example, let's say I've got the following code:
listed_products = ['1', '2', '3', '4', '5']
#Then, I would like to do something like SELECT * FROM products where id not in
#(listed_products), and save the result in @products
I know the above SQL syntax won't work, but I just wanted to give you guys the idea of what I want to achieve.
Is开发者_StackOverflow中文版 there a "rails way" for doing this?
Thanks in advance!
Yes, you can do the following (Rails 2.3.x):
listed_products = [1,2,3,4,5] Product.find(:all, :conditions => ["id NOT IN (?)", listed_products])
Or this in Rails 3.0.x:
listed_products = [1,2,3,4,5] Product.where("id NOT IN (?)", listed_products)
Pan's answer is correct, but you can also use scopes in 2.3.8, which lets you chain with other scopes for the class:
class Product
...
named_scope :excluding_ids, lambda { |*ids|
if ids.count==0 then
{}
else
{:conditions => ["id NOT IN (?)",ids]}
end
}
...
end
Then you can chain with other scopes in your class. Say you have a scope named :active. Then you can do:
Products.active.excluding_ids(*listed_products).find :all, ... more conditions ...
and it would be independent of order of the scopes:
Products.excluding_ids(*listed_products).active.find :all, ..
The best I can think of is:
SELECT * FROM products where id not = '1' and id not = '2' (etc...)
Not what you're after I'm sure, but it may be the only way!
精彩评论