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 Post
called comments_count
. Add an index on this column, and then you can select the most popular posts by:
# app/models/post.rb
scope :popular, lambda { order("comments_count DESC").limit(10) }
Check out the ActiveRecord associations class methods document for more info on counter-caches.
精彩评论