Friday, December 7, 2007

ActiveRecord find - Eager loading - :include - deep hierarchy of associations

While including a deep hierarchy of associations, I found a strange issue. Here is a contrived bit of code to describe the issue:

Post.find(:all, :include => [{ :comments => [:replies, { :author => :gravatar }] } ])


A comment has_many replies which I want to pull in via eager loading. At the same time I also want to pull in the author and gravatar pictures.

The issue here is you can only have one argument that is a key-value pair and should be the last one. So the following doesn't seem to work:

Post.find(:all, :include => [{ :comments => [ { :replies => :author}, { :author => :gravatar }] } ])

nor does this

Post.find(:all, :include => [{ :comments => [{ :author => :gravatar }, :replies] } ])


I will post an update when I figure out how to get the author for each reply eager loaded as well.

1 comment:

jt archie said...

I believe this will work for you. I had the same problem today.

Post.find(:all, :include => [ :comments => [:replies, :author => [:gravatar] ] ])