Derek J
Derek J

Reputation: 807

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!

Upvotes: 1

Views: 98

Answers (1)

Jeriko
Jeriko

Reputation: 6637

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.

Upvotes: 2

Related Questions