Reputation: 379
I have two tables, People and Vehicles. Vehicles belongs to People.
I have a report/query that shows which people do not have a vehicle. Im trying to incorporate it into my rails app so that it runs when someone wants to see this information. I decided to write a scope for it, but cannot get the scope working properly. Code is below. Any ideas?
scope :person_has_no_vehicle, -> { joins(:vehicles).where('Vehicles.person_id IS NULL')}
Query is below
SELECT DISTINCT
People.ID,
People.nam_first,
People.nam_last
FROM
People
LEFT JOIN Vehicles ON People.ID = Vehicles.person_id
WHERE
Vehicles.person_id IS NULL
Upvotes: 0
Views: 32
Reputation: 14402
The joins
method always performs an INNER JOIN
, but your original SQL query uses LEFT JOIN
.
scope :person_has_no_vehicle, -> { joins("LEFT OUTER JOIN vehicles ON vehicles.person_id = people.id").where('Vehicles.person_id IS NULL')}
Upvotes: 1