require 'time' class Api::V1::TestController < ApplicationController def index…
- User
require 'time'
class Api::V1::TestController < ApplicationController def index departure_station = params[:departure]&.upcase destination_station = params[:destination]&.upcase time = params[:time].present? ? Time.parse(params[:time]) : nil exclude = params[:restrict]&.downcase == 'true'
codeif departure_station && destination_station schedules = Schedule.joins(:stations) .where("stations.name LIKE ? OR stations.name LIKE ? OR stations.name = ? OR stations.name = ?", "#{departure_station} %", "#{destination_station} %", "#{departure_station}", "#{destination_station}") .group('schedules.id') .having('COUNT(DISTINCT stations.name) >= 2') .distinct .includes(:stations, route: :bus_schedule) trips = schedules.map do |schedule| stations = schedule.stations.order(:id) station_names = stations.map(&:name) departure_index = station_names.index { |name| name =~ /#{departure_station}/i } destination_index = station_names.index { |name| name =~ /#{destination_station}/i } if departure_index && destination_index && departure_index < destination_index departure_station_data = stations[departure_index] departure_time = Time.parse(departure_station_data.departure_time) next if time && departure_time < time 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 } trip_data[:stations] = trip_data[:stations][departure_index..destination_index] if exclude trip_data end end.compact sorted_trips = trips.sort_by do |trip| time_str = trip[:stations].find { |station| station[:station] =~ /#{departure_station}/i }[:departureTime] Time.parse(time_str) end render json: sorted_trips, status: :ok else render json: { error: 'Departure and destination stations are required. ' }, status: :unprocessable_entity end - Assistant
- User
PG::GroupingError: ERROR: column "schedules.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT DISTINCT "schedules"."id" AS t0_r0, "schedules"."rout... ^
- Assistant
It seems like you've encountered another
PG::GroupingErrordue to the use of thedistinctmethod after applying thegroupclause. In PostgreSQL (and SQL in general), when you use aGROUP BYclause, you can only select columns that are either included in theGROUP BYor are part of an aggregate function. Since thedistinctkeyword is used without any aggregation, it conflicts with the statement you previously had.