fetching from sql is pretty slow, increase efficency class Api::V1::Schedules2Controller…
- User
fetching from sql is pretty slow, increase efficency class Api::V1::Schedules2Controller < ApplicationController def index departure_station = params[:departure] destination_station = params[:destination]
codeif departure_station.present? && destination_station.present? valid_schedules = Schedule.joins(route: :bus_schedule) .joins('JOIN stations AS departure_stations ON departure_stations.id = routes.departure_station_id') .joins('JOIN stations AS destination_stations ON destination_stations.id = routes.destination_station_id') .where('departure_stations.name = ?', departure_station) .where('destination_stations.name = ?', destination_station) .where('departure_stations_routes_stations.position < destination_stations_routes_stations.position') .select('schedules.*, routes.bus_schedule_id, routes.bus_schedule.vehicle_number') .distinct # Process valid schedules to get trip information with stations sorted by position vehicle_trips = valid_schedules.map do |schedule| { trip: schedule.trip, stations: schedule.stations.order(:position).map do |station| { name: station.name, arrivalTime: station.arrival_time, departureTime: station.departure_time } end } end.group_by { |data| data[:vehicle_number] } # Return data formatted as JSON 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 - Assistant