Can someone help me understand how to convert this sql query to a named_scope or maybe a method?
Background: A trip can have many trip_runs. I’m trying to be able to say TripRun.upcoming and return only valid runs from valid trips based on the following query
SELECT r.*
FROM trip_run r
LEFT JOIN trips t
ON r.trip_id = t.id
WHERE r.starts_on > NOW()
AND t.is_booked = 1
AND t.is_cancelled IS NULL
thank you
Based on Joshua’s answer, but for rails 2.3:
or alternatively:
That will use an INNER JOIN not a LEFT JOIN, but since you’re looking for rows with trip.is_booked set to a non-null value, the results will be the same and the query will be no slower.