要使用示波器,请使用示波器轨道

时间:2015-01-05 18:15:43

标签: ruby-on-rails activerecord

我有两张桌子,人物和车辆。车辆属于人民。

我有一个报告/查询,显示哪些人没有车辆。我试图将它合并到我的rails应用程序中,以便在有人想要查看此信息时运行它。我决定为它编写一个范围,但无法使范围正常工作。代码如下。有什么想法吗?

scope :person_has_no_vehicle, -> { joins(:vehicles).where('Vehicles.person_id IS NULL')}

查询在

下面
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

1 个答案:

答案 0 :(得分:1)

joins方法始终执行INNER JOIN,但原始SQL查询使用LEFT JOIN

scope :person_has_no_vehicle, -> { joins("LEFT OUTER JOIN vehicles ON vehicles.person_id = people.id").where('Vehicles.person_id IS NULL')}