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!

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Aug 21, 2015 at 21:41
\$\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
answered Aug 22, 2015 at 7:45
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.