Including associations optimization in Rails
- by Vitaly
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?