Reputation: 34023
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
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