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]
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 = { 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 end end
db structure
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
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.