zerosum dirt(nap)

evolution through a series of accidents

zerosum dirt(nap)

has_much :confusion, :about => "string #{interpolation}"

June 05, 2007 by nap · Comments

No matter how flexible ActiveRecord’s associations become, there’s always going to be a time when you want to override it’s baked-in smarts with your own custom SQL query. Fortunately, we can do just that with the :finder\_sql option. Use it to manually specify the association that should be returned.

There’s one gotcha to be aware of though: if you need to do any variable interpolation in the string (and you most likely will), make sure to use single quotes instead of the usual doubles:

has_many :transfers, :finder_sql => 
  'SELECT * FROM transfers ' +
  'WHERE sender_id = #{id} or receiver_id = #{id}'

When you use double quotes, the string interpolation happens immediately (when the class is first loaded), thus obtaining the object ID of the class in memory. Using single quotes, the interpolation occurs within the context of your object instance, which is what you’re expecting.

blog comments powered by Disqus