2011-02-08 75 views
2

我正在使用Ruby on Rails 2.3.8,並且想要獲取尚未添加到listed_products陣列的所有@products如何在以下情況下模擬NOT IN SQL條件

例如,假設我有以下代碼:

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 

我知道上面的SQL語法將無法正常工作,但我只是想給你們的我想要什麼的想法實現。

這樣做有沒有「軌道方式」?

提前致謝!

+0

這似乎是重複的:http://stackoverflow.com/questions/4818466/rails -find-records-that-are-present-another-join-table/4818822#4818822 – Nuby 2011-02-08 19:03:01

回答

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) 
+0

您仍然可以在Rails 2.3.x中使用範圍: – 2011-02-08 20:28:46

-1

我能想到的最好的是:

SELECT * FROM products where id not = '1' and id not = '2' (etc...) 

不是你什麼,我敢肯定之後,但它可能是唯一的出路!

1

潘的答案是正確的,但你也可以使用在範圍2.3.8,它可以讓你與其他作用域鏈類:

class Product 
    ... 
    named_scope :excluding_ids, lambda { |*ids| 
     if ids.count==0 then 
     {} 
     else 
     {:conditions => ["id NOT IN (?)",ids]} 
     end 
    } 
    ... 
end 

然後你可以鏈在你的班上其他範圍。假設你有一個名爲:active的作用域。然後,你可以這樣做:

Products.active.excluding_ids(*listed_products).find :all, ... more conditions ... 

,這將是獨立的範圍的順序:

Products.excluding_ids(*listed_products).active.find :all, ..