【发布时间】:2014-11-22 19:42:46
【问题描述】:
每个度假村都有很多雪情报告。 我想获取每个度假村的最新雪情报告,其中表 snow_reports 中的 snow_summit 字段应 > 0 。
所以我尝试在resort_id 上选择不同的,这是snow_reports 中的fkey,并按updated_at 排序,但这不可能,因为选择中没有updated_at。
那么如何在 rails4(在 postgres 上)中仅获取关联模式的最新记录?
SnowReport belongs_to Resort
Resort has_many snow_reports
Table snow_reports has id,resort_id,updated_at,snow_summit
理想情况下,出于性能原因将结果连接起来。
我的方法失败了
SnowReport.includes(:resort).select(:resort_id).group(:resort_id).having('max(snow_summit)> 0').order('max(snow_reports.updated_at) DESC')
因为 SnowReport.id 为 nil
#<ActiveRecord::Relation [#<SnowReport id: nil, resort_id: 1735>, ...
编辑:
我在纯 sql 中找到了解决方案。 如何将其转换为 rails ?
select * from resorts where id in (select distinct(resort_id) from snow_reports where snow_summit > 0 and created_at > (now()- interval '3 days')
and created_at in (select max(created_at) from snow_reports group by resort_id));
【问题讨论】:
-
你的表里有没有这种规格的记录
标签: ruby-on-rails postgresql rails-activerecord