简体   繁体   English

如何计算 Rails 中父记录列表的子记录总数?

[英]How to count total child records of a list of parent records in Rails?

I have two models: Team and Player.我有两个模型:Team 和 Player。 Players belong to Teams and Teams have_many Players.玩家属于团队并且团队有_many Players。

If I have an array of teams returned as current_user.teams, how can I count the total number of players on all those teams?如果我有一组作为 current_user.teams 返回的球队,我如何计算所有这些球队的球员总数?

I tried doing the following:我尝试执行以下操作:

current_user.teams.collect { |team| team.players }.count

But that just counts the number of teams as each array of team.players is stored as one row in the current_user.teams array even though each record of team.players is an array with many records, each is only being counted once.但这只是计算团队的数量,因为每个 team.players 数组在 current_user.teams 数组中存储为一行,即使 team.players 的每条记录都是一个包含许多记录的数组,每条记录只计算一次。

How can I break out the team.players arrays to count each player in them in the final count?我怎样才能打破 team.players arrays 以在最终计数中计算其中的每个玩家?

Array.collect runs the block for each element from the array and returns a new array, and hence you should use sum Array.collect为数组中的每个元素运行块并返回一个新数组,因此您应该使用sum

try,尝试,

current_user.teams.collect { |team| team.players }.sum

note that, if the there are overlapping team players, this would not give count of unique players.请注意,如果有重叠的团队玩家,则不会计算唯一玩家。

If you have such a use case, then you can try @jvillian's suggestion,如果你有这样的用例,那么你可以试试@jvillian 的建议,

Player.where(team_id: current_user.teams).count

Try:尝试:

Player.where(team_id: current_user.teams).count

I strongly suggest you read the guide on the ActiveRecord Query Interface .我强烈建议您阅读ActiveRecord 查询接口上的指南。

BTW, collect iterates the ActiveRecord::Relation (or whatever type of enumerable you have), which strikes me as unnecessary when you can simply run the query.顺便说一句, collect迭代ActiveRecord::Relation (或您拥有的任何类型的enumerable ),当您可以简单地运行查询时,这让我觉得没有必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM