Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3 getting the count of the records that have more than one associate records (has_many)

I can get the collection of accounts that have more than one user:

Account.group('accounts.id HAVING count(users.id) > 1').joins(:users)

But, as soon as I call .count on that object, I get a huge explosion:

(0.3ms) SELECT COUNT(*) AS count_all, accounts.id HAVING count(users.id) > 1 AS accounts_id_having_count_users_id_1 FROM "accounts" INNER JOIN "users" ON "users"."account_id" = "accounts"."id" GROUP BY accounts.id HAVING count(users.id) > 1 ActiveRecord::StatementInvalid: PG::Error: ERROR: syntax error at or near "AS" LINE 1: ...unt_all, accounts.id HAVING count(users.id) > 1 AS accounts...

It seems that in postgres, the actual query I want is:

select count(*) from (SELECT accounts.id FROM "accounts" INNER JOIN "users" ON "users"."account_id" = "accounts"."id" GROUP BY accounts.id HAVING count(users.id) > 1) as a;

How can I get activerecord to generate this (or a comparable) query?

like image 867
patrick Avatar asked Apr 24 '13 18:04

patrick


1 Answers

active record supports 'having' as a method. So you could do your query this way:

Account.joins(:users).select('accounts.id').group('accounts.id').having('count(users.id) > 1')
like image 146
Kreich Avatar answered Oct 21 '22 03:10

Kreich