How to pass an Array to the IN clause of a flat query?

Asked

Viewed 75 times

0

I am using Activerecord to run queries in several different databases. In one of the queries, I have to do the following:

publications_to_read = [1,2,3,4]
ActiveRecord::Base.connection.execute("ALTER TABLE publications SET readed = TRUE WHERE id IN (#{publications_to_read});")

If I were doing this from a class I inherited from ActiveRecord::Base, there would be a much more intuitive way to do this, but that’s not the case.

What I need is to interpolate this array in the query so that the final result looks like this:

publications_to_read = [1,2,3,4]
# Query usando o array adaptado
ActiveRecord::Base.connection.execute("ALTER TABLE publications SET readed = TRUE WHERE id IN ('1', '2', '3', '4');")

Can anyone tell me how I could achieve this result? I’ve tried to do something like publications_to_read.join(',') but it didn’t work. The array is converted into a single String and gives error.

2 answers

0

You are not using Activerecord. You are sending SQL commands in a direct connection to the BD. If you want to use the abstraction that Activerecord provides:

class Publication < ActiveRecord::Base 
end

Publication.find([1,2,3,4]).update_all(readed: true) #=>sem callbacks ou validations, em um único commando SQL

Publication.find([1,2,3,4]).each {|pub| pub.update(readed: true)} #=>com callbacks e validations, comandos SQL individuais

0

Tried to make sure the end result was exactly "'1','2','3','4'"?

Try using the Join like this: \'#{publications_to_read.join('\',\'')}\'.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.