获取 rails 中模型的所有关联数

Get count of all associations to a model in rails

我有一个模型 A 作为:

class A < ActiveRecord::Base
  belongs_to :bp, class_name: "B", foreign_key: :bp_id
  belongs_to :cp, class_name: "B", foreign_key: :cp_id
end

我有一个查询,我试图从模型 A.

中获取模型 B 的所有关联的大小

我通过 bp 获取所有关联的计数,然后 cp 并将两者相加来实现它。

total_count = bp_size + cp_size

是否可以在单个查询中从 A 获得所有关联到 B model 的总和?

我的确切查询如下:

bp_size = E.where(f_id: g.joins(:f)).joins(bp: :s).size

cp_size = E.where(f_id: g.joins(:f)).joins(cp: :s).size

上面的查询经历了多级关联,但后来我通过 bpcp 加入它以获得适当的大小。我想避免 运行 查询两次

我对AR所谓的“助手”一无所知,但这完全可行:

query = <<-SQL
  SELECT 
    (SELECT COUNT(*) FROM a LEFT JOIN b ON (a.bp_id = b.id)) +
    (SELECT COUNT(*) FROM a LEFT JOIN b ON (a.cp_id = b.id))
SQL
A.connection.execute(query).to_a.first.first

动态解决方案

def self.associations_counts_hash(model, association_types)
  associations = model.reflections.collect do |a, b| 
    b.plural_name if association_types.include?(b.macro)
  end.compact

  query = model.all.includes(associations)

  associations.map do |association| 
    [
      association, 
      query.map { |u| u.send(association).size }.sum
    ] 
  end.to_h
end

associations_counts_hash(User, [:belongs_to])

虽然无法找到一个好的解决方案来避免对每个关联进行查询。