9
\$\begingroup\$

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!

\$\endgroup\$

1 Answer 1

9
\$\begingroup\$

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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.