如何急切地加载嵌套关联与count

时间:2013-12-04 16:41:24

标签: ruby-on-rails activerecord

我有4个模型,在一组链接的has_many关系中:

Account
  has_many :source_configs
  has_many :fetches, :through => :source_configs

SourceConfig
  has_many :fetches

Fetch
  has_many :social_contents

SocialContent
  # end of the line

帐户,我想获得所有关联的 SourceConfigs ,所有 Fetches 与每个SourceConfig相关联,以及计数 SocialContent 的em>。

我想尽可能少地使用查询。目前,访问计数会导致每个获取的“SELECT COUNT(*)...” - 这需要一段时间。

目前,我的控制器 #show 方法看起来像

@account = Account.includes(:source_config => :fetches).find(params[:id])

在视图中,我引用:

@account.fetches.each do |fetch|
  fetch.count
end

会导致多次SELECT COUNT()调用。

我知道如何编写SQL以包含选择Fetch对象的计数:

%{
  left outer join (
    select sc.fetch_id as fetch_id, count(*) as social_contents_count
    from social_contents sc
    group by sc.fetch_id
  ) sc_count on (sc_count.fetch_id = fetches.id)
}

这可能不完全正确,但足够好 - 我可以调整它,这不是真正的问题。

真正的问题是我无法弄清楚如何将该声明打包到包含调用中以使其正常工作。

创建命名范围对我来说不起作用(虽然我可能做错了)。

# in source_config - doesn't work
scope :fetches_with_social_content_count, :class_name => "Fetch" do |foo|
  fetches_with_social_content_count
  joins( %{ left outer join (
              select sc.fetch_id as fetch_id, count(*) as social_contents_count
              from social_contents sc
              group by sc.fetch_id
            ) sc_count on (sc_count.fetch_id = fetches.id)})
end

# try to use it: no worky
@account = Account.includes(:source_configs => :fetches_with_social_content_count).find(params.require(account_param))

有什么想法吗?

0 个答案:

没有答案