2012-07-12 76 views
4

我正在使用acts_as_commentable_with_threading gem使用戶能夠評論我的博客文章。獲取最多評論對象

我現在想要做的是顯示大多數評論的帖子,但我不知道如何查詢它們(並且據我所知,該gem不提供此類方法)。你能寫一些提示或想法如何實現這樣的事情嗎?

回答

5

以下是我用來返回已發佈最多項目的頂級用戶的方法。它可以幫助你解決你的問題。我將它放在Application Helper中,因爲它是我的側面導航欄的一部分,並將在Web應用程序的每個頁面上使用。

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 

在我看來,我有

<% top = top_posters() %> 
<% for t in top %> 
    <li><%= link_to t.username, user_path(t) %> 
     (<%= t.posts.public_posts.count %>)</li> 
<% end %> 
+0

是的,我認爲這是它:)我在我的執行中找不到錯誤:https://gist.github.com/3098896如果您有時間並希望檢查它,我會非常感激(專業版瑕疵是這個查詢返回完全糟糕的'comments_count'數字) – mbajur 2012-07-12 15:36:10

+0

我認爲這是因爲commentable_id是多態設計的一部分,您需要返回任何文章和ID匹配的目標。檢查您的數據庫,以查看除目標或來源字段中的文章之外是否還有其他許多其他內容。所以它基本上也會匹配碰巧具有相同ID的任何其他模型。 – kobaltz 2012-07-12 15:39:02

+0

哦,對了,我已經完全忘記了這一點,現在它的工作:)謝謝你很多//解決問題的帖子 – mbajur 2012-07-12 15:57:02

2

對於Rails開發4+

你應該使用這樣的事情:

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) 
+1

它和原始問題中發佈的解決方案有什麼不同? – mbajur 2015-01-18 06:59:29