Eager loading is nice with the include attribute
Post.find(:all, :include => :author)
I’m wondering if you can also eager load counts, like if I wanted to get the number of comments for each post, without loading all the comments themselves?
Maybe something like
Post.find(:all, :include => [:author, "count(comments)")
I suppose I could use a count_cache column. But doing it all in an include would be really beautiful, if it’s possible.
Extra bonus points if someone can show how to not only get the count, but put some conditions too, like count of only posts which have been approved.
In MySQL at least, it is faster to do these as two separate calls because you get to avoid the join. I know this doesn’t answer your question, but it seems like you’re trying to get better speed and doing
Then
Is faster and more memory efficient (for the database) than if you retrieve both in one query.