# Write Safer Where Clauses With Placeholders

Ruby has a super ergonomic syntax for string interpolation. This can make it tempting to build up ActiveRecord `where` clauses like so:

```ruby
def get_book_by_title(title)
  Book.where("lower(title) = #{title.downcase}")
end
```

The `where` clause, as written, is vulnerable to a SQL injection attack.

There are two kinds of placeholder syntax that you can use instead handle sanitization of the SQL.

```ruby
def get_book_by_title(title)
  Book.where("lower(title) = ?", title.downcase)
end
```

You can use multiple `?` in the query and they same number of following arguments will be interpolated in order.

There is also the keyword placeholder syntax which can give you more flexibility and make the SQL read more clearly.

```ruby
def get_book_by_title(title)
  Book.where("lower(title) = :title", title: title.downcase)
end
```

[source](https://devdocs.io/rails~5.2/activerecord/querymethods#method-i-where)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ploegert.gitbook.io/til/programmy/rails/write-safer-where-clauses-with-placeholders.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
