Follow Along as I Stumble on the Path to Learning RoR

Ordering Query Results by Count

I had two models Article and Comment where I wanted to find out which articles had the most comments.

class Comment < ActiveRecord::Base
belongs_to :article
end

class Article < ActiveRecord::Base
has_many :comments
end

I found out how to do this using this Stack Overflow question which said create a new scope, such as this in the Article.rb model:

scope :top5,
select(“articles.id, OTHER_ATTRS_YOU_NEED, count(comments.id) AS comments_count”).
joins(:comments).
group(“articles.id”).
order(“comments_count DESC”).
limit(5)

Then in your controller, you can set the scope to a variable:

@most_popular = Article.top5

and in your view:

<% @most_popular.each do |most_popular| %>

# fields to display

<% end %>

Advertisements

Comments are closed.