HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Summing the size/count of associations for multiple records

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thesummingsizerecordsformultipleassociationscount

Problem

I'm working on a plain Ruby class within a Rails application.

For the total_leg_count method---is that the best way to go about achieving what I want? I feel like there's potentially a better way.

class AircraftTimeReport

  ...

  def total_leg_count
    count = 0
    active_flights_within_timeframe.includes(:legs).each do |flight|
      count += flight.legs.size
    end
    count
  end

  private

  def active_flights_within_timeframe
    @aircraft.flights.within_timeframe(from_datetime, to_datetime).not_cancelled
  end
end

report = AircraftTimeReport.new(@aircraft)
puts report.total_leg_count


An Aircraft has_many Flights and a Flight belongs_to Aircraft.

A Flight has_many Legs and a Leg belongs_to a Flight.

I've seen other solutions that use Arel or plain SQL but I can't seem to wrap my head around it.

Also, I'm finding it difficult to unit test this method, which is why I'm wondering if there's a better way!

Solution

Equivalent, but functional and idiomatic:

def total_leg_count
  active_flights_within_timeframe.includes(:legs).map { |fl| fl.legs.size }.sum
end


This pure SQL query should be equivalent and more performant:

def total_leg_count
  active_flights_within_timeframe.includes(:legs).count(:legs)
end

Code Snippets

def total_leg_count
  active_flights_within_timeframe.includes(:legs).map { |fl| fl.legs.size }.sum
end
def total_leg_count
  active_flights_within_timeframe.includes(:legs).count(:legs)
end

Context

StackExchange Code Review Q#101611, answer score: 9

Revisions (0)

No revisions yet.