如何在以下情况下模拟NOT IN SQL条件

max*_*rez 2 ruby-on-rails

我正在使用Ruby on Rails 2.3.8,我希望得到所有@products尚未添加到listed_products数组中的内容.

例如,假设我有以下代码:

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
Run Code Online (Sandbox Code Playgroud)

我知道上面的SQL语法不起作用,但我只是想让你们了解我想要实现的目标.

这样做是否有"轨道"?

提前致谢!

Pan*_*kos 11

是的,您可以执行以下操作(Rails 2.3.x):

listed_products = [1,2,3,4,5]
Product.find(:all, :conditions => ["id NOT IN (?)", listed_products])

或者在Rails 3.0.x中:

listed_products = [1,2,3,4,5]
Product.where("id NOT IN (?)", listed_products)