patternrubyrailsMinor
Summing the size/count of associations for multiple records
Viewed 0 times
thesummingsizerecordsformultipleassociationscount
Problem
I'm working on a plain Ruby class within a Rails application.
For the
An Aircraft
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!
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_countAn 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:
This pure SQL query should be equivalent and more performant:
def total_leg_count
active_flights_within_timeframe.includes(:legs).map { |fl| fl.legs.size }.sum
endThis pure SQL query should be equivalent and more performant:
def total_leg_count
active_flights_within_timeframe.includes(:legs).count(:legs)
endCode Snippets
def total_leg_count
active_flights_within_timeframe.includes(:legs).map { |fl| fl.legs.size }.sum
enddef total_leg_count
active_flights_within_timeframe.includes(:legs).count(:legs)
endContext
StackExchange Code Review Q#101611, answer score: 9
Revisions (0)
No revisions yet.