class Api::V1::Schedules2Controller < ApplicationController def index departurestation =…
- User
class Api::V1::Schedules2Controller < ApplicationController def index departure_station = params[:departure] destination_station = params[:destination]
if departure_station.present? && destination_station.present? valid_schedules = Schedule.joins(route: :bus_schedule) .joins(:stations) .where(stations: { name: [departure_station, destination_station] }) .distinct .group_by { |schedule| schedule.route.bus_schedule.vehicle_number } trips = [] valid_schedules.each do |vehicle_number, schedules| vehicle_trips = schedules.select do |schedule| dep_index = schedule.stations.index { |s| s.name == departure_station } dest_index = schedule.stations.index { |s| s.name == destination_station } dep_index.present? && dest_index.present? && dep_index < dest_index end.map do |schedule| { vehicle_number: vehicle_number, trip: schedule.trip, stations: schedule.stations.map { |station| { station: station.name, arrivalTime: station.arrival_time, departureTime: station.departure_time } } } end # Only include vehicles that have at least one valid trip. trips.concat(vehicle_trips) if vehicle_trips.any? end render json: trips, status: :ok else render json: { error: 'Departure and destination stations are required.' }, status: :unprocessable_entity endend end
optimize above code using below logic
schedules = Schedule.joins(:stations) .where(stations: { name: [departure_station, destination_station] }) .group('schedules.id') .having('COUNT(DISTINCT stations.name) = 2') .distinct .includes(:stations, route: :bus_schedule) - Assistant
To optimize the provided
Schedules2Controller#indexaction with the given logic, we can eliminate the unnecessary joins and grouping by vehicle number, as the new logic does not rely on vehicle numbers being grouped. Instead, we will be filtering out the schedules that have both departure and destination stations using the clause. Here is the revised action incorporating the suggested logic: