Search code examples
ruby-on-railspostgresqlprepared-statement

Remove quotes from parameterized query


I'm using postgresql and ruby on rails and I'm trying to parameterize my query but when I do, it adds quotes on the params filling my place holder. Here's a simple example:

query = <<-SQL
   select * from table1 ?
SQL

When I execute the above query like this:

result = Table1.find_by_sql([query, "where table1.locations IN (1,2,3)"])

It will execute the query like this with the quotations around the condition:

select * from table1 'where table1.locations IN (1,2,3)'

But I want:

select * from table1 where table1.locations IN (1,2,3)

Solution

  • You can't bind parts of the query like that, only values. If you want to have a dynamic where clause you'll have to resort to string concatenation:

    result = Table1.find_by_sql([query + " where table1.locations IN (1,2,3)")