rails 3获取具有多个关联记录(has_many)的记录的计数 [英] rails 3 getting the count of the records that have more than one associate records (has_many)

查看:90
本文介绍了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')

这篇关于rails 3获取具有多个关联记录(has_many)的记录的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆