Q:

How to restrict displaying information on show page based on condition using has_many through?

So I'm trying to display on my Region show page a list of job openings ONLY if they reside in the right location. 
My models look like the following:
class Region < ApplicationRecord
 has_many :locations, dependent: :destroy
 has_many :careers, through: :locations
end

class Location < ApplicationRecord
 belongs_to :region
 has_many :careers
end

class Career < ApplicationRecord
 belongs_to :location
end

Region has the following fields: name, url_name 
Locations has the following fields: name, address, city, state, postal_code, region_id
Careers has the following fields: name, url_name, description, location_id

So in my Region show I have:
<% if Career.location_id == Region.location.id %>
   <% Career.all.limit(3).each do |career| %>
      <%= career.name %>
      <%= career.location.city %>
   <% end %>
 <% end %>

This actually results in undefined method `location_id' for my Regions show. I've also tried doing something like:
<% if Career.location.city == Region.location.city %>

I end up getting undefined method 'location' instead. Is this an association issue?

A:

You are using instance attributes (location_id) on the Class. You can only use instance attributes in individual objects of the class. In your controller you must find the appropriate object (record in the table) to use the attribute. But in this case it is not necessary to do it, as the region will have access to its careers in a direct manner:
def show
  @region = Region.find(params[:id])
  @careers = @region.careers
end

Then you can use @careers in the show view.
<% @careers.each do |career| %>
  <%= career.name %>
  <%= career.location.city %>
<% end %>

Or even show a partial:
<%= render @careers %>

views/careers/_career.html.erb
<%= career.name %>
<%= career.location.city %>

