Justin D.
Justin D.

Reputation: 4976

Rails - Order videos by comments count

I have a Video model and a VideoCommentone with an association to Video.

I am trying to find the most commented videos.

How can I do that?

Upvotes: 0

Views: 93

Answers (1)

Anthony Alberto
Anthony Alberto

Reputation: 10395

You should implement a counter_cache :

class Video < ActiveRecord::Base
  has_many :video_comments, :counter_cache => true
end

You'll have to create an attribute called video_comments_count on the videos table to make this work. You'll then be able to sort by this attribute.

Rails will automatically increment the counter cache for you on video comment creation and decrement on deletion

Upvotes: 3

Related Questions