I am struggling with converting a sql query in rails.
Background
I have 3 tables named bus,stop and schedule. Bus table has fields id, and name. Stop table has fields id, and name. Schedule table has fields id,bus_id,stop_id,arrival,and bustag.
This is the query i have in sql
select A.bus_id as busid, A.stop_id as source, A.arrival as atime, B.arrival as dtime from
(SELECT * from schedules as S where S.stop_id = #{startStopId}) A
inner join
(SELECT * from schedules as S where S.stop_id = #{endStopId}) B
on A.bustag = B.bustag
where A.arrival < B.arrival
and A.arrival > CURTIME();
In rails I have done this so far
@possible_buses = Schedule.where(stop_id: [startStopId,endStopId])
Now I want to do same as mysql query that is I want to further process this list of possible buses get list of buses at startStop who's bustag equals bustag of the buses at endStop where arrival time is less at startStop than arrival time at endStop.
I would highly appreciate if someone can help me out. I am not good in rails query and this would help me a long way.
Sample Tables
BusTable StopTable ScheduleTable
id Name id Name id bus_id stop_id arrival bustag
1 ttc(inbound) 1 mall 1 1 1 3:00 1
2 ttc(outbound) 2 home 2 1 2 3:15 1
3 downtown 3 1 3 3:30 1
4 uptown 4 1 4 3:45 1
5 1 1 3:15 2
6 1 2 3:30 2
7 1 3 3:45 2
8 1 4 4:00 2
9 2 4 2:55 3
10 2 3 3:10 3
11 2 2 3:25 3
12 2 1 3:35 3
13 2 4 3:10 4
14 2 3 3:20 4
15 2 2 3:30 4
16 2 1 3:45 4
Sample Query and Expected Output
For instance if user wants to go from the Mall at 2:30 to uptown Then the following ids should be returned from the schedule : -> 1,5. Since Both the Ids will get you the bus_id that take can you from the mall to uptown.
I Hope this is more clear. please feel free to ask for more information. Thanks.