Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails SQL query, passing array of ids to sql WHERE...IN clause

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?

like image 618
Jim Avatar asked Dec 04 '22 01:12

Jim


1 Answers

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

like image 126
lei liu Avatar answered Dec 14 '22 22:12

lei liu