Including associations optimization in Rails

Posted by Vitaly on Stack Overflow See other posts from Stack Overflow or by Vitaly
Published on 2010-04-14T18:43:07Z Indexed on 2010/04/14 18:53 UTC
Read the original article Hit count: 232

Hey,

I'm looking for help with Ruby optimization regarding loading of associations on demand.

This is simplified example. I have 3 models: Post, Comment, User. References are: Post has many comments and Comment has reference to User (:author). Now when I go to the post page, I expect to see post body + all comments (and their respective authors names). This requires following 2 queries:

select * from Post -- to get post data (1 row)
select * from Comment inner join User -- to get comment + usernames (N rows)

In the code I have:

Post.find(params[:id], :include => { :comments => [:author] }

But it doesn't work as expected: as I see in the back end, there're still N+1 hits (some of them are cached though). How can I optimize that?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord