> For the complete documentation index, see [llms.txt](https://ploegert.gitbook.io/til/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ploegert.gitbook.io/til/programmy/rails/bind-parameters-to-activerecord-sql-query.md).

# Bind Parameters To ActiveRecord SQL Query

Many of the connection query methods that come with `ActiveRecord` accept an optional `binds` parameter. This can be used to safely inject parameters into the query.

Here's a SQL query we could use with one of these methods:

```ruby
sql = <<-SQL
  select
    coalesce(places.latitude, 41.8781) latitude,
    coalesce(places.longitude, -87.6298) longitude
  from places
  join appointments
    on places.id = apointments.places_id
  where appointments.id = $1
    and status = $2
SQL
```

Notice the `$1` and `$2`, those are what will be bound to the two parameters included as `binds`.

```ruby
connection = ActiveRecord::Base.connection

binds = [[nil, appt_id], [nil, input_status]]
coords = connection.select_one(sql, nil, binds)

coords
#=> { "latitude": 41.8781, "longitude": -87.6298 }
```

Notice the `binds` is an array of tuples. It's the second value in each tuple that gets bound the corresponding binding indicator in the sql. The syntax is a bit awkward since it is a lower-level API, however once you know it, you can manage.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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/bind-parameters-to-activerecord-sql-query.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.
