time is in the format of string with 08:32 am so edit code to sort class…
- User
time is in the format of string with 08:32 am so edit code to sort
class Api::V1::SchedulesController < ApplicationController def index departure_station = params[:departure] destination_station = params[:destination]
if departure_station.present? && destination_station.present? # Get all schedules that contain the departure station schedules = Schedule.joins(:stations).where(stations: { name: departure_station }).distinct.includes(:stations, route: :bus_schedule) trips = [] schedules.each do |schedule| stations = schedule.stations.order('arrival_time ASC') station_names = stations.map(&:name) if station_names.index(departure_station) && station_names.index(destination_station) && station_names.index(departure_station) < station_names.index(destination_station) trip_data = { trip: schedule.trip, vehicle_number: schedule.route.bus_schedule.vehicle_number, stations: stations.map do |station| { station: station.name, arrivalTime: station.arrival_time, departureTime: station.departure_time } end } trips << trip_data end end # Sort trips based on the arrival time of the departure station sorted_trips = trips.sort_by { |trip| trip[:stations].find { |station| station[:station] == departure_station }[:arrivalTime] } # Return the sorted trips data render json: sorted_trips, status: :ok else # Error response if parameters are missing render json: { error: 'Departure and destination stations are required.' }, status: :unprocessable_entity endend end
- Assistant