I'm new to Rails (and SQL) and am trying to write an AREL query for a transit app.
The Background:
I have a few different models (Stop, Route, Trip, and StopTime). A Route has many trips, and a Trip has many stop times. This represents one route (eg: Green Line) having many trips throughout the day (the 6AM train, the 7AM train, etc.), that stop at a number of stops (MLK blvd, Washington blvd, etc.) according to a table of stop times.
The Objective:
Once a user has selected their Route and direction (eg: Green line towards UCLA), and we have determined their current stop via GPS, I want to show all the subsequent stops so the user can input their final destination.
The Problem:
In order to do this I'd like to write an AREL query in my controller that does the following:
For a given route (given_route.trips) and direction (trip.direction_id (which is a boolean)) I'd like to select the ONE trip that has the most stops (ie: select the trip where count of stops_times.sequence is the highest).
In other words:
- For a given route, which has (lets say) 100 trips each day, we want to:
- Select only the trips that match the direction_id (trip.direction_id)
- For these trips, we want to pick the 1 trip where the count of Trip.stop_times.sequence is the highest
Thanks in advance -- any help would be much appreciated!