2011-09-14 14 views
2

我有以下類預加載多個named_scope的計數的Rails

class Service < ActiveRecord::Base 
    has_many :incidents 
end 

class Incident < ActiveRecord::Base 
    belongs_to :service 

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

我想每個預加載事件類的罪名,這樣我的觀點可以做 類似:

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

沒有爲每個計數進行SQL查詢。我正在嘗試一種方法,選擇 但我沒有太多運氣。這是我到目前爲止有:

# 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 

這將預取一個計數,但我不知道如何做到這一點的兩個不同 named_scope。

使用counter_cache不是一個選項,因爲數據庫正在被非rails代碼寫入。

任何幫助歡迎。

回答