2

I'm trying to execute some hand-hacked SQL through ActiveRecord::Base.connection, but for readability and protection against injection, I would like to use placeholders like in this old example: find_by_sql with array format in Rails 3 instead of raw string interpolation.

None of the methods I have found on ActiveRecord::ConnectionAdapters::PostgreSQLAdapter which is the underlying class for connection appears to support this kind of behavior.

So how can do it? I want the result to be an area of hashes and I don't need to mix it with any existing ActiveRecord scopes.

Community
  • 1
  • 1
Niels B.
  • 5,912
  • 3
  • 24
  • 44
  • Hey @NielsB! Did you find a better solution? – EugZol Aug 11 '15 at 10:49
  • Nope, but based on EugZols solution, it may be possible to write a wrapper class that substitute *symbols* with escaped input. Maybe i'll give it a shot when I come back to it. – Niels B. Aug 11 '15 at 16:52

1 Answers1

-2

Yep, looks like placeholders is out of option. I used manual escaping when faced the same problem:

user_id = user_id.to_i
client = connection.quote(client.to_s)

connection.execute(
  "INSERT INTO stats (user_id, client) VALUES (#{user_id}, #{client})"
)
EugZol
  • 6,476
  • 22
  • 41