2013-04-30 91 views
0

如何在Rails中編寫where子句以測試多個值?Where子句的Rails語法

這不起作用:

where("wostatus_id = ?", 231 or 230 or 8466) 

還需要語法是這樣的:

where("wostatus_id != ?", 231 and 230 and 8466) 

感謝您的幫助!

回答

4

你可以這樣做......

where("wostatus_id IN (?)", [231, 230, 8466]) 

where("wostatus_id NOT IN (?)", [231, 230, 8466]) 
+0

感謝您的幫助! – Reddirt 2013-04-30 18:11:41

2

你可以使用正常的hash condition

Model.where(wostatus_id: [230, 231, 8466]) 

這將產生預期的 「IN」查詢。在Rails 3中,沒有辦法將其轉換爲「NOT IN」,因此您需要回到where("wostatus_id NOT IN (?)", [230, 231, 8466])方法。

在Rails 4,你應該能夠做到:

Model.where.not(wostatus_id: [230, 231, 8466]) 

參見:How to express a NOT IN query with ActiveRecord/Rails?

+0

謝謝 - 這是很好的信息。 – Reddirt 2013-05-01 14:51:09