Rails 3:通过关系获取模型数量

Rails 3: Get Count of Models via Relationship

In Ruby on Rails (3) 使用 PostgreSQL 并给出以下三个层次模型:

class Category
    has_many :posts
end

class Post
    belongs_to :category
    has_many :comments
end

class Comment
    belongs_to :post
end

有没有办法获得每个 category 的总 comment 计数,而不必遍历每个 posts

任何帮助将不胜感激,谢谢!

是的,有。您需要做的就是按您想要的列对关系进行分组:

counts_hash = 
  Comment.
  joins(post: :category).
  group("#{Category.table_name}.id").
  count

那应该 return 具有结构 category_id => comments_count

的散列

但是,这将排除所有评论为 0 的类别,因为将执行内部联接。

如果您想包括所有类别 ID,无论出于何种原因,您都必须包括一些额外的步骤:

counts_hash.tap do |hash|
  Category.pluck(:id).each do |category_id|
    hash[category_id] = 0
  end
end

或者:

# the following will return 0 as the value of any missing key
Hash.new(0).merge(counts_hash)hash