Accessing “Child” Associations in Ruby on Rails

Ruby on Rails
My good buddy Dan of helped me out with a Rails problem last night. I wanted to access the associations defined on an association of one of my model classes when calling find, in essence, accessing a “child” association. I looked high and low for this, but with no luck so Dan was able to come to my rescue. He said you can do this:

@collection = MyClass.find(:all, :conditions => ["id = ?", params[:id]], 
      :include => [:foo => [:bar]], :order => sort)

I guess using :include like this is will tell Rails and ActiveRecord that you want to include the Bar class association in the JOIN you’re doing in SQL so you can enhance your query. Makes sense, but too bad it seems to be hardly documented!

One thought on “Accessing “Child” Associations in Ruby on Rails

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.