Show the count of a has_many table in the index list of entries

Hi everyone, I have an index view, simply showing all the entries in a table. I need to add a column that shows how many entries there are in a has_many table for this main table. I also only want to count the entries that also have a blank entry in a field in that child table. Any thought appreciated - exhausted my.skills and searching :slight_smile: TIA, Dave

This sounds a lot like the counter cache feature in Rails. The only hangup is your need for the count to be conditional.

I’ve never tried it but you might be able to make it conditional by passing a scope to the belongs_to relationship. There is also the counter culture gem which has been around for a while and adds all sorts of additional features to the counter cache.

A final option is to use a sub-query. I actually wrote an article about this strategy many years ago. Not quite as optimized as a true counter cache but simpler and more dynamic and in most cases perfectly adequate performance.

1 Like

Thanks for your suggestions, I will investigate… Regards, Dave

Sounds like you just want to take advantage of some eager loading. Here’s a guess at what you want (all naming made up)…

In your controller:

@collection = IndexModel.includes(:relation)

In your view:

<% @collection.each do |index| %>
  <h1><= index.name %></h1>
  <p>Count is: <%= index.relation.length %></p>
<% end %>
<p><%= @collection.find_all{|index| index.relation.field.blank?}.length %></p>

You can also use a sub query in the select to get a count attribute.

Something like:

objects = MyObject.left_outer_joins(:join_objects).select("my_objects.*, (SELECT COUNT(*) FROM join_objects. where my_object.id = join_objects.my_object_id) as join_count")

Then you can access join_count in the index table on each row.