benc
benc

Reputation: 2018

iterating data from 2 models

In my index I'm trying to iterate through records through records in 2 models, job and employer. I've set up a has_many relationship.

Rails its throwing a undefined method `each' for #

job model

attr_accessible :title, :location   
belongs_to :employer

employer model

attr_accessible :companyname
has_many :jobs

job controller

def index
@jobs = Job.find(:all, :include => :employer)

index

<% @jobs.each do |job| %>
<%= job.title %>
<%= job.location %>

  <% job.employer.each do |employer| %>
  <% employer.companyname %>
  <% end %>
<% end %>

Upvotes: 0

Views: 58

Answers (2)

MrDanA
MrDanA

Reputation: 11647

That's because a job has one employer, not many. That's what the belongs_to means. See this Rails guide about setting up actual many-to-many relationships.

But I think in your case you do want it to be a one-to-many. Why would a job have multiple employers? Instead, just output the single employer company name.

More Info

You still want a belongs_to on your Job model. belongs_to go on models that have a foreign key referencing some other model. In this case, your Job model has an ID pointing at an Employer (it has an employer_id field). That has_one or has_many associations are for when no foreign key exists on the model but a relationship still exists.

So your Job model has a method called employer (singular) but not employers (plural) because it belongs to a single employer. An employer has many jobs under them, so the has_many association gives you a jobs (plural) method, not a job (singular) method.

The link I posted for the Rails guide does an excellent job of showing more of this, with more details and explanation, and more examples.

Addtional Code Bit

With the above, you will want to change your code to be like this:

<% @jobs.each do |job| %>
  <%= job.title %>
  <%= job.location %>

  <%= job.employer.companyname %>
<% end %>

Notice how you can go straight to accessing the attributes on the employer that you want. And that will do it!

Upvotes: 2

goddamnyouryan
goddamnyouryan

Reputation: 6906

Have you tried running this in the rails console?

Job.last.employer

If that doesn't work your relationship isn't set up properly.

Does your Job model have an employer_id field? Did you run rake db:migrate to make sure all your migrations are run?

Upvotes: 0

Related Questions