嵌套分组的代码建议ActiveRecord | Rails 5.2

问题描述 投票:0回答:1

我正在开发一个需要做一些基本统计报告的项目。例如,模型Post有一个外键字段category_id引用Category模型中的记录,而布尔字段published有一个默认值false(以及titlebodyauthor - 但它们与此问题无关)。

我想设置和嵌套分组迭代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 %>

任何有关如何修改上述代码的反馈或建议都将非常感激。谢谢

ruby-on-rails group-by rails-activerecord
1个回答
1
投票

请尝试以下查询它没有测试但我认为它应该工作

没有测试

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 %>
© www.soinside.com 2019 - 2024. All rights reserved.