baldmark
baldmark

Reputation: 707

Group by query in Rails 3

I have the (working) code

counts = Registration.select('regulator_id').group('regulator_id').count
@regulators.each {|r| r.registration_count=counts[r.id]}

which allows me to show how many Registrations there are per Regulator. The query it generates is:

SELECT COUNT("registrations"."regulator_id") AS count_regulator_id, regulator_id AS regulator_id FROM "registrations" GROUP BY regulator_id

I would like to restrict my count to those registrations from the last scrape only, with a query like:

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

but I cannot get the syntax to work either using arel or find_by_sql. I am sure this is simple when you know the answer but it has cost me ages so far.

Thanks in advance.

Upvotes: 0

Views: 3481

Answers (1)

Bonias
Bonias

Reputation: 71

Just add 'joins' and 'where'

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

Upvotes: 1

Related Questions