我正在尝试获取用户列表,以及他们在不同状态下的项目计数。
我有一个用户表,以下为我的项目表。
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] }
但是这并没有返回一些容易读的东西。理想情况下,我更喜欢像下面这样的东西,当我构建前端时,它会帮助我。
{
"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