我有(工作)代码
counts = Registration.select('regulator_id').group('regulator_id').count
@regulators.each {|r| r.registration_count=counts[r.id]}
允许我显示每个Regulator有多少个注册。它生成的查询是:
SELECT COUNT("registrations"."regulator_id") AS count_regulator_id, regulator_id AS regulator_id FROM "registrations" GROUP BY regulator_id
我想将我的计数限制在最后一次搜索的注册中,查询如下:
select
regulator_id, count(*)
from
registrations inner join
regulators on regulators.id = registrations.regulator_id
where
registrations.updated_at > regulators.last_scrape_start
group by
regulator_id
但我无法使用arel或find_by_sql来使用语法。我相信当你知道答案时这很简单,但到目前为止我花了很多钱。
提前致谢。
答案 0 :(得分:1)
只需添加'joins'和'where'
Registration.joins(:regulator).where('registrations.updated_at > regulators.last_scrape_start').select('regulators.id').group('regulators.id').count