TIL: ActiveRecord hash conditions and parameterized conditions

2021-12-03 00:00:00 +0000 UTC

ActiveRecord allows the use of ‘hash conditions’ to construct WHERE clauses like so:

Person.where(name: "Tyler")

You can also use hash conditions when joining:

Person.joins(:orders).where(orders: { pending: true })

But you cannot use hash conditions to create queries based on SQL keywords like LIKE. Instead you must use string conditions and placeholders like this Postgres example:

Person.where("email LIKE ?", "%gmail.com")

Parameterized queries like this allow SQL injection mitigations to be applied by ActiveRecord where

Person.where("email LIKE %#{INPUT}")

would be unsafe!

Tags: til ruby rails