【发布时间】:2018-07-20 17:14:37
【问题描述】:
我想查询将结果添加到数组中,例如:
app/models/user.rb
query = self.patients.where(["created_at >= ? and created_at >= ? and created_at >= ?", Time.zone.now.beginning_of_day, Time.now.beginning_of_week, Time.now.beginning_of_month]).to_a
预期结果:
query
=> [3, 5, 12]
当前结果:
Patient Load (0.8ms) SELECT `patients`.* FROM `patients` WHERE `patients`.`medic_id` = 1 AND (created_at >= '2018-07-20 00:00:00' and created_at >= '2018-07-16 05:00:00' and created_at >= '2018-07-01 05:00:00')
=> #<ActiveRecord::AssociationRelation []>
without to_a method => [#<ActiveRecord::AssociationRelation []>]
with to_a method => []
型号
class User < ApplicationRecord
has_many :patients, dependent: :destroy
end
class Patient < ApplicationRecord
belongs_to :user
end
我收到一个空数组/AssociationRelation,我怎样才能得到包含一天、一周、一个月开始的患者数量的数组,像这样query = [3, 5, 12]?
注意,使用:
- Mysql:版本 15.1 Distrib 10.1.34-MariaDB,适用于 Linux (x86_64),使用 读线 5.1
- 红宝石:2.3.3p222
- 导轨:5.0.0.1
- 活动记录:5.0.0.1
【问题讨论】:
-
这不是 ActiveRecord 的工作方式。你不能用一个
select返回这些值,你需要三个子查询。
标签: mysql ruby-on-rails ruby activerecord