Sql Rails中多个命名\u作用域的预加载计数
我在下列课程中有一门课Sql Rails中多个命名\u作用域的预加载计数,sql,ruby-on-rails,database,activerecord,Sql,Ruby On Rails,Database,Activerecord,我在下列课程中有一门课 class Service < ActiveRecord::Base has_many :incidents end class Incident < ActiveRecord::Base belongs_to :service named_scope :active, lambda ... named_scope :inactive, lambda ... end 这将预取一个计数,但我不确定如何对两个不同的计数进行预取
class Service < ActiveRecord::Base
has_many :incidents
end
class Incident < ActiveRecord::Base
belongs_to :service
named_scope :active, lambda ...
named_scope :inactive, lambda ...
end
这将预取一个计数,但我不确定如何对两个不同的计数进行预取
命名范围
使用计数器缓存不是一个选项,因为数据库是由非rails代码写入的
欢迎任何帮助 我最后为此写了一篇文章
<% Service.all.each do |s| %>
<%= s.active.count =>
<%= s.inactive.count =>
<% end %>
# 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