2016-02-12 133 views
0

我有一個ID的數組我想保留,然後刪除其餘的,我們有3種類型的用戶,AdminsInvestorsStudents。我有的列表是Students的ID,所以我想刪除所有。Rails where.not with multiple arguments

如果我嘗試運行此

User.where.not(id: GOOD_LIST).count(:all) 

我會得到15000條記錄。但如果我嘗試添加附加條件

User.where.not(id: GOOD_LIST).where(type: "Student").count(:all) 
or 
User.where.not('id IN ? AND type = ?', GOOD_LIST, "Student").count(:all) 

它將返回0條記錄。

我嘗試了使用where方法

User.where('id NOT IN ?', GOOD_LIST).where(type: "Student").count(:all) 

,但有以下錯誤消息

(10.7ms) SELECT COUNT(*) FROM "users" WHERE "users"."type" = 'Student' AND (id NOT IN 39999,40000,40001,40002,40003,40004,40005,40006,40007,40008) 
PG::SyntaxError: ERROR: syntax error at or near "39999" 
LINE 1: ... WHERE "users"."type" = 'student' AND (id NOT IN 39999,4000... 

什麼是這樣做的最佳方式?

+2

'.where('id NOT IN(?)',GOOD_LIST)''? –

+0

你試過這個'User.where(「id not in(?)AND type =?」,GOOD_LIST,「Student」)。count' –

+0

另外,它是''student''還是''Student'' D b? –

回答

1

生成的SQL缺少列表中的括號。所以我們應該將它們添加到您的模板中,像這樣

.where('id NOT IN (?)', GOOD_LIST)