Q:

Count the number of records in group_by clause

I have the following categories grouped together
@categories = Category.all.group_by { |c| c.name }

In my view I am displaying the category names like so
<% @categories.each do |c, v| %>
  <li><%= link_to c, blog_path(:name => c) %></li>
<% end %>

Which gives this for example
Ruby
Ruby On Rails
CSS

What i want to achieve is next to each category name have the total number of posts with that category name, so
Ruby(2)
Ruby On Rails(10)

So i have tried
@categories = Category.joins(:posts).all.group_by { |c| c.name }

Which results in only the categories with a post object being displayed (previously all categories would display, regardless of whether they had a post object) and in my view i tried
<% @categories.each do |c, v| %>
  <li><%= link_to c, blog_path(:name => c) %><%= c.count %></li>
<% end %>

Which is outputting nothing. I thought i would ask how to approach this before i confuse the matter, if someone could explain the answer aswell that would be greatly appreciated
Many Thanks

A:

It's confusing to call the grouped categories @categories because that makes it sound like a collection of Category objects, when it's actually a Hash.  Using descriptive names, including in your loop, makes your code much clearer.
Try this:
@category_groups = Category.includes(:posts).all.group_by { |c| c.name }

and the view
<% @category_groups.each do |name, categories| %>
  <li><%= link_to name, blog_path(:name => name) %> (<%= categories.map{|category| category.posts.size}.sum %> posts)</li>
<% end %>

