I have a has_many
comment post model. Each post has a thread identifier (but there is no model called Thread).
So, if I want to count the number of threads in this post, I do something like
> post.comments.count(:thread, :distinct => true) SELECT COUNT(DISTINCT "comments"."thread") FROM "comments" WHERE "comments"."post_id" = 3
And it works great. But what if I want to count the number of threads with just one comment?
> post.comments.group(:thread).having('COUNT(*) == 1').count SELECT COUNT(*) AS count_all, thread AS thread FROM "comments" WHERE "comments"."post_id" = 3 GROUP BY thread HAVING COUNT(*) == 1 ORDER BY id
So, I have OrderedHash instead of Integer. And I have to take an unnecessary step
> post.comments.group(:thread).having('COUNT(*) == 1').count.count
Is there a better solution?
Ximik source share