# Quick Tip: Rails Named Bind Variables

> How to use named bind variables in a Ruby on Rails query to increase readability and reduce duplication.

- Author: Curtis Miller
- Published: 2009-10-01
- Categories: rails, how-to
- Canonical URL: https://millarian.com/posts/quick-tip-rails-named-bind-variables/

Have you ever come across a Ruby on Rails query that has so many conditions that it's hard to figure out what is being replaced where? While this can be somewhat mitigated by using [Rails named scopes](https://millarian.com/posts/quick-tip-named_scope/), you can also use named bind variables to make it easier to read. Named bind variables replace the question marks with symbols and you supply a hash with values for the matching symbol keys:

```ruby
Company.find(:first, :conditions => [
  "state = :state AND name = :name AND division = :division AND created_at > :some_date",
  { :state => :approved, :name => 'Velocity Labs', :division => 'First', :some_date => '2009-02-27' }
])
```

This is also very handy when you have the same value for multiple parameters, since it will replace all matching bind variables with the value (e.g., the current time).

```ruby
Event.find(:first, :conditions => [
  "state = :state AND starts_at <= :now AND ends_at >= :now",
  { :state => :active, :now => Time.zone.now }
])
```

## References

- [ActiveRecord::Base API documentation](http://api.rubyonrails.org/classes/ActiveRecord/Base.html)
