如何使用连接从范围访问数据

时间:2015-01-06 16:33:43

标签: ruby-on-rails activerecord

我有两张桌子,人物和车辆。我创建了一个范围,显示哪些人没有车辆。

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| %>

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

<% if test.vehicles.person_id == NIL %>&lt; - 这不起作用,但你明白了。

1 个答案:

答案 0 :(得分:1)

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

# 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

我不明白为什么你会从车辆表中访问数据&#34;,你想要的范围恰恰相反:没有任何车辆关联的人。

无论如何,如果你真的想测试是否没有与People记录对应的Vehicle,试试这个:

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