it only retrive departure and destination stations, also retrive stations in between…
- User
it only retrive departure and destination stations, also retrive stations in between them
class Api::V1::SchedulesController < ApplicationController def index departure_station = params[:departure] destination_station = params[:destination]
if departure_station.present? && destination_station.present?
Start by fetching schedules that include both departure and destination stations
schedules = Schedule.joins(:stations, route: :bus_schedule) .where(stations: { name: [departure_station, destination_station] }) .distinct .includes(:stations, route: :bus_schedule)
Iterate through schedules to filter valid ones and prepare the response data
vehicle_trips = schedules.each_with_object({}) do |schedule, acc|
Extract station names to check the order without triggering extra queries
station_names = schedule.stations.map(&:name) puts station_names
Ensure that the destination comes after the departure
if station_names.include?(departure_station) && station_names.include?(destination_station) && station_names.index(departure_station) < station_names.index(destination_station)
vehicle_number = schedule.route.bus_schedule.vehicle_number trip_data = { trip: schedule.trip, stations: schedule.stations.map do |station| { station: station.name, arrivalTime: station.arrival_time, departureTime: station.departure_time } end }
Accumulate trips for each vehicle_number
acc[vehicle_number] ||= [] acc[vehicle_number] << trip_data end end
Render the final JSON response
render json: vehicle_trips.map { |vehicle_number, trips| { vehicle_number: vehicle_number, trips: trips } }, status: :ok else render json: { error: ‘Departure and destination stations are required.’ }, status: :unprocessable_entity end end end
db scheme
app/models/bus_schedule.rb
class BusSchedule < ApplicationRecord has_many :routes end
app/models/route.rb
class Route < ApplicationRecord belongs_to :bus_schedule has_many :schedules end
app/models/schedule.rb
class Schedule < ApplicationRecord belongs_to :route has_many :stations end
app/models/station.rb
class Station < ApplicationRecord belongs_to :schedule end
- Assistant
- User
only sort time time wise no need to bus wise
- Assistant
- User
use Time.parse because time is in the from of 08:32 am
- Assistant