I've got a the next classes

class Service < ActiveRecord::Base
    has_many :incidents
end

class Incident < ActiveRecord::Base
    belongs_to :service

    named_scope :active, lambda ...
    named_scope :inactive, lambda ...
end

I am attempting to preload the counts of every occurrences class to ensure that my view can perform something similar to:

<% Service.all.each do |s| %>
    <%= s.active.count =>
    <%= s.inactive.count =>
<% end %>

Without creating a SQL query for every count. I am trying a strategy with choose but I am not getting much luck. This is what I've to date:

# In Service class
def self.fetch_incident_counts
  select('services.*, count(incidents.id) as acknowledged_incident_count').
    joins('left outer join incidents on incidents.service_id = services.id').
    where('incidents.service_id = services.id AND ... same conditions as active scope').
    group('services.id')
end

Which will prefetch one count, but I am unsure how to get it done for 2 different named_scope.

Using counter_cache isn't a choice since the database has been written to by non-rails code.

Any help welcome.

I wound up writing a jewel with this. https://github.com/smathieu/preload_counts