Reputation: 4474
I'm using acts_as_commentable_with_threading gem to make users able to comment my blog posts.
What I want to do now is to display most commented posts but I have no idea how to query them (and as far as I know, the gem not provides such method). Can you write me some tips or ideas how to achieve something like that?
Upvotes: 4
Views: 1195
Reputation: 41
For Rails 4+
You should use something like this:
Article.select("articles.*, COUNT(commentable_id) as comments_count")
.joins("LEFT JOIN comments AS comments ON comments.commentable_id = articles.id")
.group("comments.commentable_id")
.order("comments_count DESC")
.where("commentable_type = 'Article'")
.limit(5)
Upvotes: 2
Reputation: 7070
Here is a method that I use to return the top users that have posted the most items. It may help you with your issue. I put this in the Application Helper because it is part of my side navigation bar and will be used on every page in the web application.
def top_posters
User.all(:select => "users.*, COUNT(user_id) as post_count",
:joins => "LEFT JOIN posts AS posts ON posts.user_id = users.id",
:group => "posts.user_id",
:order => "post_count DESC",
:limit => 5)
end
In my view, I have
<% top = top_posters() %>
<% for t in top %>
<li><%= link_to t.username, user_path(t) %>
(<%= t.posts.public_posts.count %>)</li>
<% end %>
Upvotes: 5