In an Active Record where string, how do positional ? and :named placeholders bind their values, and how do they handle arrays?
answer
- values after the template string
- ? in order, :name from a hash
- array expands into a comma list
- you write the IN parentheses
- PreparedStatementInvalid on a count mismatch
basics
~20 sEach ? takes the next extra argument and each :name takes the matching key of a trailing hash. Rails binds and quotes every value, expands an array into a comma list, and raises ActiveRecord::PreparedStatementInvalid when the counts do not match.
solid answer
~40 sWith a string condition you write the SQL template and pass values separately: `Apartment.where("rent BETWEEN ? AND ?", min, max)` fills placeholders in order, while `where("rent <= :max AND bedrooms >= :beds", max: 1800, beds: 2)` fills them by name from a hash. Rails never pastes the raw value into the template: each value is handed to the adapter as a bound value, so strings are quoted and escaped for you. An array expands into a comma-separated list, so `where("city IN (?)", ["Lyon", "Nice"])` works, but you write the parentheses yourself. A record becomes its id, an Active Record relation becomes an inline subquery, and an empty array becomes `NULL`, which matches nothing. A wrong number of values, or a named key missing from the hash, raises `ActiveRecord::PreparedStatementInvalid` as soon as `where` is called.
code
ruby · 15 lines# positional
Apartment.where("rent BETWEEN ? AND ?", params[:min_rent], params[:max_rent])
# named, with a repeated key
Apartment.where(
"rent <= :max AND (deposit IS NULL OR deposit <= :max)",
max: params[:max_rent]
)
# arrays expand; you write the parentheses
Apartment.where("LOWER(city) IN (?)", %w[lyon nice])
# wrong count is caught before any SQL runs
Apartment.where("rent BETWEEN ? AND ?", 900)
# => ActiveRecord::PreparedStatementInvalid: wrong number of bind variables (1 for 2)go deeper
Remember the two styles, ? in order and :name from a hash, and never build a where string with #{} interpolation of user input.
Explain what each value type becomes: arrays expand to lists inside parentheses you write, records become ids, relations become subqueries, and count mismatches raise PreparedStatementInvalid when where is called.
Know where placeholders stop helping: identifiers, sort directions and LIKE wildcards need allow-lists or escaping, and nil needs the hash form to become IS NULL.
Set the team rule: hash conditions first, placeholder strings for the remainder, and allow-lists for anything that is not a value, so review can spot string building at a glance.
## Why string conditions exist at all The hash form of `where` covers equality, `IN`, `IS NULL` and ranges. Anything else, such as `rent < deposit * 3`, `LOWER(city) = ?`, `LIKE`, or a database function, needs a **string condition**. The rule for string conditions is simple: **the template is code you wrote, and every user-supplied value travels separately as a placeholder value**. Building the string with Ruby interpolation (`"rent < #{params[:max]}"`) turns input into SQL text; that vulnerability is its own topic, and placeholders are the everyday way to avoid it. ## Positional and named placeholders Active Record accepts two placeholder styles, and they cannot be mixed in one call: - **Positional `?`**: values follow the template as extra arguments and fill the question marks in order: `Apartment.where("rent BETWEEN ? AND ?", 900, 1800)`. - **Named `:key`**: a single hash follows the template and each `:key` is looked up in it: `Apartment.where("rent <= :max AND bedrooms >= :beds", max: 1800, beds: 2)`. A name can repeat, which is handy when the same value appears twice. PostgreSQL casts such as `rent::numeric` are not mistaken for placeholders. - **Array form**: `where(["rent <= ?", 1800])` is the same call with the template and values wrapped in one array, which is convenient when the condition is built elsewhere and passed around. Rails wraps the whole string in parentheses, so a condition containing `OR` cannot leak into the conditions chained around it. ## What each kind of value becomes | Value passed | What lands in the SQL | |---|---| | string, number, date, time | one bound value, quoted and type-cast by the adapter | | array `["Lyon", "Nice"]` | a comma list of bound values: `city IN ('Lyon', 'Nice')` | | empty array `[]` | `NULL`, so `IN (?)` matches no row | | an Active Record object | its id (`id_for_database`) | | an Active Record relation | its SQL inlined as a subquery | Two consequences matter in practice: 1. You write the parentheses for `IN (?)` yourself; Rails only supplies the list. 2. An empty array does not raise; it quietly matches nothing. If an empty selection should mean "no filter", skip the call. ## How the values reach the database The placeholder template becomes a bound SQL literal node in Arel. When the statement is compiled: - With **prepared statements enabled** (the default on the PostgreSQL and SQLite adapters), values are sent as real bind parameters beside the SQL text. - With prepared statements disabled, the adapter substitutes each value as a correctly quoted literal. Either way, the value is quoted by the connection that knows the database's escaping rules, never by string concatenation in your code. ## Choosing a form | Need | Form | |---|---| | equality, IN, NULL, ranges | hash: `where(rent: 900..1800)` | | comparison between columns, SQL functions, LIKE | string with `?`: `where("LOWER(city) = ?", city.downcase)` | | many values or one value used twice | string with `:name`: `where("rent <= :max OR deposit <= :max", max: 1800)` | | condition built in one place and applied elsewhere | array: `cond = ["rent <= ?", 1800]; where(cond)` | Named placeholders read better once a condition holds more than two or three values, because the hash documents what each value means and the order no longer matters. ## Errors are raised early Placeholder bookkeeping is checked in Ruby when `where` is called, before any SQL is sent: - `where("rent BETWEEN ? AND ?", 900)` raises `ActiveRecord::PreparedStatementInvalid` with "wrong number of bind variables (1 for 2)". - `where("rent <= :max", min: 900)` raises `ActiveRecord::PreparedStatementInvalid` with "missing value for :max". Because the error comes from `where` itself, it surfaces when the relation is built, not when it is first iterated in a view. ## Traps worth naming - `where("landlord_id = ?", nil)` writes `landlord_id = NULL`, which matches nothing; only hash conditions turn `nil` into `IS NULL`. - Placeholders bind **values**, not identifiers: a column name or sort direction cannot be a `?`. Choose those from an allow-list in code. - A `LIKE` pattern built as `"%#{term}%"` is still bound safely, but `%` and `_` typed by the user act as wildcards; escaping them is the job of a separate sanitizing helper. - The `%s` sprintf style in a `where` template leaves the surrounding quotes to you; `?` and `:name` do not, so prefer them.
- Can a ? placeholder stand in for a column name, as in Apartment.where("? <= 1800", params[:column])?No. Placeholders bind values, so the name arrives as a quoted string literal (`'rent' <= 1800`), never as an identifier, and the query compares a constant instead of the column. Pick identifiers from an allow-list in code, for example `column = %w[rent deposit].include?(params[:column]) ? params[:column] : "rent"`, then use the hash form `where(column => ..1800)`.
- Why might you still prefer the hash form even when a string with placeholders would work?The hash form casts values through the attribute's type, rewrites `nil` to `IS NULL`, and produces predicates that `where.not`, `or` and `rewhere` can recognise by column. A string condition is opaque to those tools. Use strings only for what hashes cannot say.
- What does where("city IN (?)", []) return?No rows. The empty array is turned into `NULL`, so the SQL reads `city IN (NULL)`, which is never true. It does not raise, which is why an empty filter array should usually skip the call instead.
- Placeholders just interpolate the value into the string with quotes added
- You can bind a column name or sort direction with a ? placeholder
- where("city IN ?", list) works because Rails adds the parentheses
- A wrong number of ? values only fails when the database parses the SQL
- You can mix ? and :named placeholders in one where call
- where("landlord_id = ?", nil) generates landlord_id IS NULL