Reputation: 379
I have two tables, People and Vehicles. I created a scope that shows which people do not have 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)}
In my View I have
<% @person.person_has_no_vehicle.each do |test| %>
How would I access data from my vehicles table?
I.E.
<% if test.vehicles.person_id == NIL %>
<-- That does not work, but you get the general idea.
Upvotes: 1
Views: 91
Reputation: 54882
First, I suggest you some refactor:
# 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) }
Then in your view you can use:
<% 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
I don't understand why you "would access data from the vehicles table", the scope you want is the exact opposite: People without any vehicle associated.
Anyway, if you really want to test if there is not Vehicle corresponding to the People record, try this:
<% People.without_vehicle.each do |people| %>
<%= "THIS GUY OWNS AT LEAST 1 VEHICLE!!" if people.vehicles.present? %>
Upvotes: 1