【发布时间】:2018-11-24 20:32:14
【问题描述】:
我在使用 postgres 的 Rails 5 上,我有一个用户表和一个报告表。用户有很多报表,每天都需要创建这些报表。我想获取所有未归档、今天未完成报告的用户,并显示昨天的报告说明(如果有)。
以下是模型:
用户模型
# == Schema Information
#
# Table name: users
#
# id :bigint(8) not null, primary key
# name :string not null
# created_at :datetime not null
# updated_at :datetime not null
# archived :boolean default(FALSE)
#
class User < ApplicationRecord
has_many :reports
end
报告模型
# == Schema Information
#
# Table name: reports
#
# id :bigint(8) not null, primary key
# notes :text
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint(8)
#
class Report < ApplicationRecord
belongd_to :user
end
这是我想要从这个查询中得到的一个例子:
用户表
------------------------------------------------------------------------------------
| id | name | archived | created_at | updated_at |
------------------------------------------------------------------------------------
| 1 | Jonn | false | 2018-05-11 00:01:36.124999 | 2018-05-11 00:01:36.124999 |
------------------------------------------------------------------------------------
| 2 | Sam | false | 2018-05-11 00:01:36.124999 | 2018-05-11 00:01:36.124999 |
------------------------------------------------------------------------------------
| 3 | Ashley | true | 2018-05-11 00:01:36.124999 | 2018-05-11 00:01:36.124999 |
------------------------------------------------------------------------------------
报告表(想象一下这份报告是昨天的)
--------------------------------------------------------------------------------------
| id | user_id | notes | created_at | updated_at |
--------------------------------------------------------------------------------------
| 1 | 1 | Nothing | 2018-06-13 16:32:05.139284 | 2018-06-13 16:32:05.139284 |
--------------------------------------------------------------------------------------
愿望输出:
-------------------------------------------------------------------------------------------------------
| id | name | archived | created_at | updated_at | yesterdays_notes |
-------------------------------------------------------------------------------------------------------
| 1 | Jonn | false | 2018-05-11 00:01:36.124999 | 2018-05-11 00:01:36.124999 | Nothing |
-------------------------------------------------------------------------------------------------------
| 2 | Sam | false | 2018-05-11 00:01:36.124999 | 2018-05-11 00:01:36.124999 | NULL |
-------------------------------------------------------------------------------------------------------
我能够通过编写原始 SQL 获得所需的查询结果,但在尝试将其转换为活动记录查询时遇到了很多问题。这是使用scenic gem 的合适场景吗?
这是原始 SQL 查询:
SELECT u.*, (
SELECT notes AS yesterdays_notes
FROM reports AS r
WHERE r.created_at >= '2018-06-13 04:00:00'
AND r.created_at <= '2018-06-14 03:59:59.999999'
AND r.user_id = u.id
)
FROM users AS u
WHERE u.archived = FALSE
AND u.id NOT IN (
SELECT rr.user_id
FROM reports rr
WHERE rr.created_at >= '2018-06-14 04:00:00'
);
【问题讨论】:
-
我没有经验
scenic建议或劝阻,尽管在转换为 AR 时有什么问题。这也可以转换为连接查询。
标签: ruby-on-rails postgresql activerecord