Topic: Showing associated objects?

Hello all.

I'm new to the rails (and the entire web application) development scene.  I've been working on building a rudimentary job tracking database and I am running into difficulties with showing associated objects.

For example:

Jobs have a has_many relationship to Samples, withsamples having a belongs_to relationship with jobs.  All of the scaffolding and associations work, but I would like to be able to generate a table of the samples that belong to a job in the view method.

So far, I have done this in the jobs_controller:

def show
    @job = Job.find(params[:id], :include => [:samples])
end

Which presumably tells it to seek out associated samples for the job being viewed.  That's pretty much where I get stuck.  I've been attempting to generate the table this way in the show.rhtml file:

<h1>Associated Samples</h1>

<table border = "1">
  <tr>
    <th>TEST</th>
    <th>TEST</th>
  </tr>
 
  <% for samples in @job %>
  <tr>
    <td><%= sample.description %></td>
    <td><%= sample.quantity %></td>
  </tr>
<% end %>
</table>


But...  Well, it doesn't appreciate it.  Everything else seems to be working in terms of the associations.  Samples can be associated with jobs and in the case of the test data I am using, there is a sample associated with the job I'm attempting to show.  Any help or suggestions would be greatly appreciated.

Re: Showing associated objects?

Check out the documentation on Active Record. It really helped me when trying to understand how relations work. Make sure to look at the docs for the "find" method and the "has_many" method as that should help you in this specific case.

http://api.rubyonrails.org/classes/Acti … /Base.html


I'd also recommend getting the Agile Web Development with Rails book. Get the 2nd edition if you don't mind reading a beta PDF until it comes out. It will really help you understand how relationships work.
http://www.pragmaticprogrammer.com/titles/rails2/


As for your specific problem, put this in the controller:

def show
    @job = Job.find(params[:id])
end

And this in the view:

<% for sample in @job.samples %>
  <tr>
    <td><%= sample.description %></td>
    <td><%= sample.quantity %></td>
  </tr>
<% end %>

Easy, no? smile

Railscasts - Free Ruby on Rails Screencasts

Re: Showing associated objects?

Really easy.  Thanks for the help!  I've been trying to work things through with the O'Reilly Rough Cuts book, but the early version is somewhat lacking in some areas.