rails 3获取具有多个关联记录(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)
但是,当我在该对象上调用.count时,就会发生巨大爆炸:
But, as soon as I call .count on that object, I get a huge explosion:
(0.3ms)选择COUNT(*)AS count_all,accounts.id拥有count(users.id)> 1 AS account_id_having_count_users_id_1 FROM"accounts" INNER JOIN"users" ON"users"."account_id" ="accounts"."id" GROUP BY account.id拥有计数(users.id)> 1ActiveRecord :: StatementInvalid:PG ::错误:错误:"AS"或附近的语法错误第1行:... unt_all,accounts.id拥有count(users.id)> 1个AS帐户...
(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...
似乎在postgres中,我想要的实际查询是:
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;
如何获取activerecord来生成此(或类似的)查询?
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')