ruby-on-rails - Rails:按用户分组项目,然后计数状态
问题描述
我正在尝试获取用户列表,以及他们在不同状态下拥有的项目的计数。
我有一个用户表,以下是我的项目表。
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
推荐阅读
- c# - NET Core 3 服务 - 服务管理器不会等待服务启动
- testng - TestNg 报告仅在最后生成
xml上的标签 - java - 如何使用 javax.json lib 迭代更多 JsonObject
- java - 使用 jsoup 或任何其他库通过原始 xpath 从 HTML 中删除元素
- java - 在java jtextfield中按3组用空格分割数字
- c++ - 构造和销毁对象
- javascript - 多个滑块在代码中重复我自己
- c++ - MySQL命令阶段没有来自服务器的响应
- python - Python 错误 FileNotFoundError: [Errno 2] 没有这样的文件或目录
- swift - 当父 viewControler 上发生操作时,如何刷新 childViewControler 对象