2012-02-25 85 views
0

我有(工作)代碼集團通過查詢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。當你知道答案時,我相信這很簡單,但迄今爲止我花了很多時間。

在此先感謝。

回答

1

只需添加 '聯接' 和 '地點'

Registration.joins(:regulator).where('registrations.updated_at > regulators.last_scrape_start').select('regulators.id').group('regulators.id').count 
+0

感謝。我什至不記得我正在做什麼愚蠢的錯誤,但我必須嘗試幾件非常接近的事情。 – baldmark 2012-02-25 19:31:56