Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql Rails中多个命名\u作用域的预加载计数_Sql_Ruby On Rails_Database_Activerecord - Fatal编程技术网

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