Friday, December 14, 2007

deep eager loading with ActiveRecord

I was going through Rails today cleaning up some code and found and interesting thing with ActiveRecord. I have always known it was capable of eager loading of associations. For example, a blog post can have many comments.


@posts = Post.find(:all,:include=>[:comments])

Well a comment is associated is written by a user and say you want to eager load the user information too. Well it appears that ActiveRecord supports eager loading of associations with associations. Meaning, I can load the user information for each comment associated with a post.


@posts = Post.find(:all,:include=>[:comments=>[:user])

This is amazing. I had not known about this feature, but decided to give it a try. This saves in time with alot optimizations that I tried with eager loading and caching of associations' associations.

Update: It has been brought to my attention that this actually documented. This either proves I need to read the entire document or it needs to be better organized. :)

No comments: