user4440189
user4440189

Reputation:

show all companies that have a job

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

Answers (3)

evanbikes
evanbikes

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

Michal
Michal

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

Yaro
Yaro

Reputation: 568

Please, replace <% unless company.job.nil? %> with <% if company.jobs.any? %>

Upvotes: 2

Related Questions