Rails:按用户对项目进行分组,然后对状态进行计数

Rails: Group projects by user then status with a count

我正在尝试获取用户列表,以及他们处于不同状态的项目数量。

我有一个用户 table,我的项目如下 table。

create_table :projects do |t|
  t.string      :slug, null: false
  t.belongs_to  :user
  t.string      :title
  t.text        :description
  t.integer     :is_status
end

在我的 user 模型中,我有项目所需的关联。

class User < ApplicationRecord
  has_many :projects

project 模型我已将关联添加到 user

class Project < ApplicationRecord
  belongs_to        :user

现在我试过了..

Project.includes(:user).group(:user_id, :is_status)
.select(: user_id, :is_status, "SUM(is_status) as is_status_count").where.not
(user_id: 1).where.not(is_status: nil).order("user_id DESC").collect{ |a
| [a.user.name, a.is_status, a.is_status_count] }

但这并不是 return 容易阅读的内容。理想情况下,我更喜欢以下内容,owl 在我构建前端时会有所帮助。

{
  "user_1": {
    "status_1": 1,
    "status_2": 4,
    "status_3": 10
  }
}

非常感谢任何帮助

让我们从您已有的查询开始

relation = Project.includes(:user).group(:user_id, :is_status)
  .select(:user_id, :is_status, "SUM(is_status) as is_status_count").where.not
  (user_id: 1).where.not(is_status: nil).order("user_id DESC")

从那里开始,我们不想将它们收集到一个数组中,而是希望以每个 user_id

具有单个键的散列结束
hash = relation.group_by { |project| project.user.name} # { "user_1": [<#Project>, <#Project>] }

现在我们要将项目数组变成一个散列,每个项目都有一个值

hash.transform_values do |projects|
  projects.map do |project|
    [project.is_status, project.is_status_count]
  end.to_h
end