Wednesday, June 20, 2007

finder_sql in HABTM

Using this "finder_sql", you can override ActiveRecord's associations in your models. Use it to manually specify the association that should be returned.

Important Note: if you need to do any variable interpolation in the string , make sure to use single quotes instead of the usual doubles:

has_many :books, :finder_sql => 'select * from books where author_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.

Enjoy Agile Programming!!!

0 comments: