Quantcast
Channel: Summing the size/count of associations for multiple records - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 2

Summing the size/count of associations for multiple records

$
0
0

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  endendreport = 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!


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>
<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596344.js" async> </script>