Preloading count of multiple named_scope in Rails
I have a the following 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'm trying to preload the counts of each incidents class so that my view can do something like:
<% Service.all.each do |s| %>
<%= s.active.count =>
<%= s.inactive.count =>
<% end %>
Without making a SQL query for each count. 开发者_StackOverflow中文版I'm trying an approach with select but I'm not having much luck. Here's what I have so far:
# 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
That will prefetch one count, but I'm not sure how to do it for two different named_scope.
Using counter_cache is not an option because the database is being written to by non-rails code.
Any help welcome.
I ended up writing a gem for this. https://github.com/smathieu/preload_counts
精彩评论