2013-05-13 54 views
0

在我的應用程序中,我必須從Facebook的評論模型中爲Post模型獲取最後/最新的兩條評論。ROR +獲取每篇文章的最新或最後兩條評論

對於每個帖子可能有評論與否。例如: -

Post 1 having 10 comments. 
Post 2 having 5 comments. 
Post 3 have no comments. 
Post 5 have 20 comments. 

現在我無法找到每條帖子的最後兩條評論以及與該帖子相關的評論總數。任何人都可以建議如何解決此問題。因爲我在腦海裏有一個非常糟糕的方法,那就是發佈Post的每個循環並找到最後/最新的2條評論。

在此先感謝。希望最好的方法/方法。

回答

0

天真的方法:假設每個崗位有一個的has_many:評論的關係,你可以嘗試:

comments = post.comments 
total_comments = comments.count 
last_two_comments = comments.last(2) 

這會給你一個職位對象的最後兩點意見。這將加載每篇文章的所有評論,因此可能不是理想的性能。或者,您可以對post_id等於相關post_id的評論進行查詢。

喜歡的東西:

Comment.where(post_id: post.id).limit(2).order("id DESC") 
相關問題