0

I have an array of ID's I would like to preserve and then delete the rest, we have 3 types of users, Admins, Investors and Students. The list I have is for Students id's, so I would like to delete all .

If I try run this

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

I will get 15k records. but if I try add an additional condition

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

It will return 0 records.

I tried just using the where method

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

but got the following error message

(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...

What is the best way of doing this?

9
  • 2
    how about .where('id NOT IN (?)', GOOD_LIST)? Commented Feb 12, 2016 at 8:02
  • have u tried this User.where("id NOT IN (?) AND type = ?", GOOD_LIST, "Student").count Commented Feb 12, 2016 at 8:06
  • Also, is it "student" or "Student" in the db? Commented Feb 12, 2016 at 8:08
  • @SergioTulentsev Your first comment should fix it. While using IN, we need to use like (?). Commented Feb 12, 2016 at 8:08
  • @SergioTulentsev Is correct, And you can write the same code as User.where.not(id: GOOD_LIST).where(type: "Student").count(:all) Commented Feb 12, 2016 at 8:10

1 Answer 1

1

That generated SQL is missing parentheses around the list. So we should add them in your template, like this

.where('id NOT IN (?)', GOOD_LIST)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.