jfredson
jfredson

Reputation: 171

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

I have two models: Team and Player. Players belong to Teams and Teams have_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?

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.

How can I break out the team.players arrays to count each player in them in the final count?

Upvotes: 1

Views: 1311

Answers (2)

jvillian
jvillian

Reputation: 20263

Try:

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

I strongly suggest you read the guide on the ActiveRecord Query Interface.

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.

Upvotes: 0

Sujan Adiga
Sujan Adiga

Reputation: 1371

Array.collect runs the block for each element from the array and returns a new array, and hence you should use 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,

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

Upvotes: 4

Related Questions