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, 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 => 'Flatterline', :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 }


Posted October 1st, 2009 at 9:30 am in Ruby on Rails | Permalink

Leave a response: