我正在开发一个需要做一些基本统计报告的项目。例如,模型Post
有一个外键字段category_id
引用Category
模型中的记录,而布尔字段published
有一个默认值false
(以及title
,body
,author
- 但它们与此问题无关)。
我想设置和嵌套分组迭代Post
模型并将Post
记录按其Category
分组,然后在每个类别中,进一步按published
字段的状态分组,为每个分组提供count
,以呈现结果类似于以下:
Categories
Tutorial
Published: 14 posts
Draft: 3 posts
Q & A
Published: 14 posts
Draft: 3 posts
Letter
Published: 14 posts
Draft: 3 posts
以下是我开始使用的非功能性代码:
<% @posts.group(:category).each do |category| %>
<% category.label %>
<% category.each.group(:published).count.each do |published_status, count| %>
<%= published_status %>: <%= pluralize(count, "post") %>
<% end %>
<% end %>
任何有关如何修改上述代码的反馈或建议都将非常感激。谢谢
请尝试以下查询它没有测试但我认为它应该工作
没有测试
categories = Category.left_outer_joins(:posts)
.select("
Categories.label,
(SELECT COUNT(posts.id) from posts where posts.published=true) as published_count,
(SELECT COUNT(posts.id) from posts where posts.published=false) as draft_count
")
.group('categories.id')
在视图中
<% categories.each do |category| %>
<%= category.label %>
<%= category.published_count %>
<%= category.draft_count %>
<% end %>