开发者

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

开发者 https://www.devze.com 2023-03-22 12:09 出处:网络
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

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

精彩评论

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