Quick Tip: Rails Named Bind Variables

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

Posted by Curtis Miller Curtis Miller

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, 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:

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).

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

References



Velocity Labs

Need web application development, maintenance for your existing app, or a third party code review?

Velocity Labs can help.

Hire us!