To convert your ActiveRecord query into a raw PostgreSQL command in Ruby on Rails, you will need to understand the SQL that ActiveRecord would generate and then you can use a find_by_sql method to execute raw SQL. Let's break down the query to get the corresponding SQL and then put it in a PostgreSQL command.
Here's the original ActiveRecord code:
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)
Now let's construct the SQL that would be equivalent to this ActiveRecord query:
SELECT DISTINCT "schedules".*
FROM "schedules"
INNER JOIN "stations" ON "stations"."schedule_id" = "schedules"."id"
LEFT OUTER JOIN "routes" ON "routes"."id" = "schedules"."route_id"
LEFT OUTER JOIN "bus_schedules" ON "bus_schedules"."route_id" = "routes"."id"
WHERE ("stations"."name" LIKE 'departure_station %' OR
"stations"."name" LIKE 'destination_station %' OR
"stations"."name" = 'departure_station' OR
"stations"."name" = 'destination_station')
GROUP BY "schedules"."id"
HAVING COUNT(DISTINCT "stations"."name") >= 2
Notice that I've added LEFT OUTER JOINs for the includes clause to load the related routes and bus_schedules, which is what .includes() does in ActiveRecord. In pure SQL, we don't have a direct way to express 'includes', so you have to explicitly join the related tables if you want that data to be loaded.
Here's how you'd execute the raw SQL in Ruby on Rails:
departure_station = 'departure_station_identifier' # Make sure to set these variables appropriately
destination_station = 'destination_station_identifier'
raw_sql = <<-SQL
SELECT DISTINCT "schedules".*
FROM "schedules"
INNER JOIN "stations" ON "stations"."schedule_id" = "schedules"."id"
LEFT OUTER JOIN "routes" ON "routes"."id" = "schedules"."route_id"
LEFT OUTER JOIN "bus_schedules" ON "bus_schedules"."route_id" = "routes"."id"
WHERE ("stations"."name" LIKE '#{departure_station} %' OR
"stations"."name" LIKE '#{destination_station} %' OR
"stations"."name" = '#{departure_station}' OR
"stations"."name" = '#{destination_station}')
GROUP BY "schedules"."id"
HAVING COUNT(DISTINCT "stations"."name") >= 2
SQL
schedules = Schedule.find_by_sql(raw_sql)
Remember to sanitize any user inputs to avoid SQL injection attacks if departure_station or destination_station are provided by users. The norm in Rails is to utilize ActiveRecord for database interactions due to the abstraction, security, and maintenance benefits it provides, so be cautious about replacing ActiveRecord queries with raw SQL.