Reputation:
I have an association between jobs and companies where company has_many: jobs
and job belongs_to: company
. Now I am trying to access a page where there are only companies that have a job, so for this i have this code in my controller
def recruiting
@companies = Company.all
end
and this is my recruiting page
<% @companies.each do |company| %>
<% unless company.job.nil? %>
<%= link_to company.name, company_path(company), title: "#{company.name}" %>
<% end %>
<% end %>
This doesn't work and gives me an error undefined method job'
Upvotes: 3
Views: 86
Reputation: 4171
If you want to only return companies with jobs and not have to worry about if/unless logic in the views, you can do:
def index
@companies = Company.joins(:jobs).uniq
end
But if you want to return companies both with and without jobs, you should be including jobs so that you aren't making a SQL call on each iteration of the loop.
@companies = Company.includes(:jobs)
Upvotes: 4
Reputation: 753
When you have a has_one relation, the form is singular (job). In has_many, there are multiple jobs, so the form is plural.
So
company.jobs.nil?
Upvotes: 0
Reputation: 568
Please, replace <% unless company.job.nil? %>
with <% if company.jobs.any? %>
Upvotes: 2