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?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With