ActiveRecord Grouping/Count Query Help Needed?

A simple option which will help to keep your query simple and readable would be to set up a counter_cache in your post-comment association so you can just add where("comments_count > 0") in your find.

Thanks for the suggestion. I think I will go with this option but I would still be curious to see if there is some combination of AR methods that can do this. – Ken Thompson Dec 17 '10 at 5:09.

Giving 'having' a try. Just hacked this together quickly.... Post. Select("posts.Id, posts.

Category_id, count(comments. Id)"). Join(:comments).

Group('posts. Category_id'). Having('count(comments.

Id) > 0') Which would translate to something like... select posts. Id, posts. Category_id, count(comments.

Id) from posts join comments on posts. Id = comments. Post_id group by posts.

Category_id having count(comments. Id) > 0 Might have to iterate on this a small bit...

(After changing "join" to "joins" to get it to compile)..this returns the Post id and Category id for one Post from each category. – Ken Thompson Dec 17 '10 at 4:58 Right - joins. Apologies.

You'll need to add 'count(comments. Id) as foo' - that'll be set foo into the post object returned and represent the number of comments in the category. Yes - example was framed around all posts - now scope it to your blog - blog.posts.

– Cory Dec 17 '10 at 17:20.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions