Find all posts by this post

I have a simple rails 3 blogging application in which posts contain many comments and commentary on the post.

I want to create an area that will retrieve all posts with more than 5 comments. What is the best way to do this without a cache counter column.

+4
source share
3 answers

How is this possible?

Post.select('posts.*, count(comments.id) as comment_count'). joins(:comments). group('posts.id'). having('comment_count > 5') 
+8
source

In Postgres 9.1, I had to set it up so that postgres did not like the conditions for computed fields or something like that.

 Post.select('posts.*, count(comments.id) as comment_count'). joins(:comments). group('posts.id'). having('count(comments.id) > 5') 
+4
source

Great answer from noodl ... thanks for that!

I needed to find - stick with the sample classes of the original question - 4 posts that were recently commented ... a small answer to noodl does the trick:

 Post.select('posts.*, max(comments.created_at) as last_commented_at'). joins(:comments). group('posts.id'). order('last_commented_at DESC'). limit(4) 

Thanks!

0
source

All Articles