2012-02-25 11 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