如何找到关联记录的最大数量? [英] How to find the maximum number of associated records?
问题描述
我有 Accounts
和 Users
.帐户 has_many :users
和用户 belongs_to :account
.
I have Accounts
and Users
. Account has_many :users
and User belongs_to :account
.
我想知道的是单个帐户拥有的最大用户数.
What I'm trying to find out is the maximum number of users any single account has.
因此,它需要遍历所有帐户,汇总每个帐户的用户数并返回每个帐户的用户数,或者理想情况下,返回所有帐户中的最大用户数.
So, it would need to cycle through all the accounts, sum up the users for each account and return the user count for each account or, ideally, just the maximum user count it found in all of them.
运行 Rails 4.0.12 和 Ruby 2.1.5.
Running Rails 4.0.12 and Ruby 2.1.5.
推荐答案
当然可以:
Account.all.each_with_object({}) do |account, hash|
hash[account.name] = account.users.count
end
这将返回所有帐户的哈希值,并将其用户总数作为其值.
That will return a hash of all accounts with their user totals as their value.
类似于:
=> { "Account1" => 200, "Account2" => 50 }
要对其进行排序,请执行类似操作
To sort it, do something like
results = Account.all.each_with_object({}) do |account, hash|
hash[account.name] = account.users.count
end
sorted = results.sort_by { |acc, ct| ct }.reverse
这篇关于如何找到关联记录的最大数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!