views:

63

answers:

1

Here I want to show the extra attribute CONFIRMED from the employments join table. What am I doing wrong?

class Job < ActiveRecord::Base    
has_many :employments, :dependent => :destroy
has_many :users, :through => :employments

class User < ActiveRecord::Base
has_many :employments 
has_many :jobs, :through => :employments


class Employment < ActiveRecord::Base
belongs_to :job
belongs_to :user  # Employment has an extra attribute of confirmed ( values are 1 or 0)

In my job view I want to show the confirmed value for each job. I just cant seem to get it. In my view i have:

<% @job.each do |job| %>
    <tr class="<%= cycle('oddrow', 'evenrow') %>">
      <td><%= link_to job.clientname, job_url(job.id) %></td>
      <td><%= job.eventtype.name %></td>
      <td><% unless job.starts_at.blank? %><%= job.starts_at.to_formatted_s(:full) %><% end %></td>
      <td>7 - 12 </td>

Here I want to show the extra attribute CONFIRMED from the employments join table. What am I doing wrong?

     <td><%= job.employment.confirmed %></td> 
     </tr>
<% end %>

Thanks

+1  A: 

Look at your Job model. You've declared it to have many employments. Calling the plural form of the association (employments) will get you a list of the employments for that job.

If you wanted only the confirmed jobs, you could add a named scope to Employment like the following:

named_scope :confirmed, :conditions => ['confirmed = ?', true]

Then calling job.employments.confirmed would give you only the confirmed employments.

Jared
Jared,I know I am missing somthing here. I just cant seem to wrap my head around it.<%= job.employments.confirmed %> I get undefined method `confirmed' for #<Class:0x23110e4>
Fresh
Since .employments is defined as has_many, it's going to return an array of all employments - and .confirmed doesn't make sense on an array. You need to loop through the returned employments and display each one; that, or if a job will only ever have one employment, the relationship should be redefined as a has_one.
Rufo Sanchez
Awesome. named_scope worked well. I just need to think of it a different way. named_scope makes more since
Fresh