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
class Article < ActiveRecord::Base
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:
select(“articles.id, OTHER_ATTRS_YOU_NEED, count(comments.id) AS comments_count”).
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 %>