Home / Learn Secure SQL / Ruby: the pg Gem and ActiveRecord Sanitization

Ruby: the pg Gem and ActiveRecord Sanitization

Positional placeholders in raw Ruby, and the ORM layer underneath.

The gistPositional placeholders in raw Ruby, and the ORM layer underneath.

The idea, explained simply

Ruby pg gem patternconn.exec_params(sql,values)$1, $2 placeholdersresult rows
Ruby pg gem pattern

Definition

Ruby's pg gem uses $1, $2 placeholders with exec_params; ActiveRecord (covered later) builds on similar safe sanitization for its own query methods.

Why you need this

Ruby code sometimes uses string interpolation heavily elsewhere in the language, which again makes it worth being explicit that SQL is the one place that habit must not be used.

How it works

Use conn.exec_params(sql, values) with $1, $2 placeholders for raw Ruby, or ActiveRecord's own parameterised finder methods for Rails apps.

Where you'll see this

  • Web application code review
  • Backend development
  • Database administration
Ruby pg gem
require 'pg'
conn = PG.connect(dbname: 'shop')
result = conn.exec_params('SELECT * FROM users WHERE email = $1', [email])
result.each { |row| puts row['name'] }
Careful:Avoid conn.exec("SELECT * FROM users WHERE email = '#{email}'") — Ruby string interpolation inside a raw SQL string is the same core problem in Ruby's own syntax.

Test what you just read

1. Ruby's pg gem uses exec_params mainly to...