【问题标题】:Preloading count of multiple named_scope in RailsRails中多个named_scope的预加载计数
【发布时间】:2011-09-14 01:28:58
【问题描述】:

我有以下课程

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 查询。我正在尝试使用 select 的方法 但我运气不好。到目前为止,这是我所拥有的:

# 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

这将预取一个计数,但我不确定如何为两个不同的 命名范围。

使用 counter_cache 不是一个选项,因为数据库是由非 Rails 代码写入的。

欢迎任何帮助。

【问题讨论】:

    标签: sql ruby-on-rails database activerecord


    【解决方案1】:

    我最终为此写了一个 gem。 https://github.com/smathieu/preload_counts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      相关资源
      最近更新 更多