3

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'

Darkmouse
  • 1,941
  • 4
  • 28
  • 52
  • This is not the best way to do it. It loops through all Company records and skip only the ones that does not have a job. You could do it directly in your SQL to save execution time. (see this answer: http://stackoverflow.com/questions/18082096/rails-4-scope-to-find-parents-with-no-children/18082147#18082147) – MrYoshiji Jan 16 '15 at 18:33

3 Answers3

4

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)
evanbikes
  • 4,131
  • 1
  • 22
  • 17
2

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

Yaro
  • 570
  • 3
  • 20
  • I have replaced with unless company.jobs.empty? and it is working –  Jan 16 '15 at 18:21
  • that was another option :P Just if you like "unless" more than "if" :P – Yaro Jan 16 '15 at 18:21
  • 2
    This is not the best way to do it. It loops through all Company records and skip only the ones that does not have a job. You could do it directly in your SQL to save execution time – MrYoshiji Jan 16 '15 at 18:33
0

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?
Michal
  • 733
  • 2
  • 6
  • 23