optimize this code require 'time' class Api::V1::SchedulesController <…
- User
optimize this code require 'time'
class Api::V1::SchedulesController < ApplicationController def index departure_station = params[:departure] destination_station = params[:destination]
codeif 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 = { vehicle_number: schedule.route.bus_schedule.vehicle_number, trip: schedule.trip, 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] } sorted_trips = trips.sort_by do |trip| time_str = trip[:stations].find { |station| station[:station] == departure_station }[:departureTime] Time.parse(time_str) # assuming arrivalTime is in “08:32 am” format end # 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 end - Assistant