开发者

Rails 3: Fastest way to determine model popularity by counting association

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜