5

Dealing with a HABTM relationship and need to write a sql query string that I can run via ActiveRecord::Base.connection.execute(my_query)

A SQL WHERE...IN clause expects an array of integer ids, something like this: "DELETE from contacts_tags where tag_id = 99 AND contact_id IN (1, 2, 3, 4)

I have an array of the ids I want to pass into the IN clause, but can't seem to format it in a way that SQL will accept.

ids_for_delete = [1, 2, 3, 4]
my_query = "DELETE from contacts_tags where tag_id = 99 AND contact_id IN (#{ids_for_delete})"
ActiveRecord::Base.connection.execute(my_query) 
    #=> There is an error in your SQL syntax.

What is the proper way to pass a array of ids to a SQL WHERE clause?

2 Answers 2

17

Try:

my_query = "DELETE from contacts_tags where tag_id = 99 AND contact_id IN (#{ids_for_delete.join(', ')})"

use the method join to generate string like "1, 2, 3, 4.."

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I must have been overthinking it.
when ids_for_delete is blank, it's going to break
@rony36 you will need to detect the array first, make sure it's not blank before you use this express.
1

You can also use ANY operate with array values:

DELETE FROM contacts_tags WHERE tag_id = 99 AND contact_id = ANY('{ #{ids_for_delete.join(",")} }'::int[])

It will not break even if you pass an empty array.

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.