Fellow Stranger
Fellow Stranger

Reputation: 34023

Order posts by most comments

User has_many Post.

Post has_many Comment.

How could I query the posts of a user, ordered by number of comments each post has?

As much of an ActiveRecord-esque answer as possible would be much appreciated.

Upvotes: 1

Views: 544

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107728

Store the comments count for posts as a counter_cache in the Comment model:

belongs_to :post, counter_cache: true

Then in your posts table, have a comments_count field that's an integer.

From there, it's easy:

Post.order("comments_count DESC")

Upvotes: 2

Related Questions