如何使用连接访问作用域中的数据

How to access data from a scope with a join

我有两个表,People 和 Vehicles。我创建了一个显示哪些人没有车辆的范围。

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

在我看来我有

<% @person.person_has_no_vehicle.each do |test| %>

我如何访问我的车辆表中的数据?

I.E.

<% if test.vehicles.person_id == NIL %> <-- 这行不通,但你明白了。

首先,我建议你进行一些重构:

# FROM
scope :person_has_no_vehicle, -> { joins("LEFT OUTER JOIN vehicles ON vehicles.person_id = people.id").where('Vehicles.person_id IS NULL').limit(100)}
# TO
scope :without_vehicle, -> { includes(:vehicles).where(vehicles: { id: nil }).limit(100) }

那么在你看来你可以使用:

<% People.without_vehicle.each do |people| %>
  # These People instances do not have any vehicle record associated
  # so `people.vehicles` in this loop should return an empty ActiveRecord::Relation

我不明白你为什么"would access data from the vehicles table",你想要的范围恰恰相反:没有任何车辆关联的人。

不管怎样,如果你真的想测试是否没有People记录对应的Vehicle,试试这个:

<% People.without_vehicle.each do |people| %>
  <%= "THIS GUY OWNS AT LEAST 1 VEHICLE!!" if people.vehicles.present? %>