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

0

I'm using ActiveRecord to run queries on 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 inheriting from ActiveRecord::Base , there would be a much more intuitive way of doing this, but that is not the case.

What I need is to interpolate this array in the query so that the end 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 already tried to do something like publications_to_read.join(',') but it did not work. The array is converted to a single String and gives error.

    
asked by anonymous 13.04.2016 / 02:22

2 answers

0

Have you tried to make the final result exactly " '1','2','3','4' "?

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

    
13.04.2016 / 02:50
0

You are not using ActiveRecord. You are sending SQL commands on a direct connection to the DB. 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
    
30.04.2016 / 04:29