Suppose I have a Post model which has_many Comments. I want to get the top 10 most popular posts based on those who have the most comments. Assuming I have hundreds of thousands of posts, what’s the most efficient way of getting those 10 top posts?
Also, how do I cache that query?
Thanks!
I’d suggest you add a counter-cache column on
Postcalledcomments_count. Add an index on this column, and then you can select the most popular posts by:Check out the ActiveRecord associations class methods document for more info on counter-caches.