集团通过查询Rails中3
问题描述:
我有(工作)代码集团通过查询Rails中3
counts = Registration.select('regulator_id').group('regulator_id').count
@regulators.each {|r| r.registration_count=counts[r.id]}
,让我来说明如何多个注册有每稳压器。它生成的查询是:
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。当你知道答案时,我相信这很简单,但迄今为止我花了很多时间。
在此先感谢。
答
只需添加 '联接' 和 '地点'
Registration.joins(:regulator).where('registrations.updated_at > regulators.last_scrape_start').select('regulators.id').group('regulators.id').count
感谢。我什至不记得我正在做什么愚蠢的错误,但我必须尝试几件非常接近的事情。 – baldmark 2012-02-25 19:31:56