In Rails, how to count the number of associated records in a collection?

Viewed 3464

I have a model named Awardunit. Awardunit have many Awardleaders. One Award unit can have one or many Award leaders.

If I get all the record or search and get a collection of records to a variable named awardunits how can I count the number of Awardleaders in all the units in this collection?

Here's what I did :

 @leaders = 0
 @awardunits.each do |unit|
      @leaders = @leaders + unit.awardleaders.size
 end

Again to count the disabled leaders I use this :

  @disabledleaders = 0
  @awardunits.each do |unit|
     @disabledleaders = @disabledleaders + unit.awardleaders.where(disabled: true).size
  end

If I use this, it will have to go through all the records every time the page loads. Isn't there a better way of doing this?

3 Answers
Related