Topic: Accessing Model Data in Views

Hi there,

i'm just starting, so my problem is pretty basic:

I'm going through a tutorial where i'm building a very basic project management application.

What i'm trying to do is to show the person associated to a specific task.

Relevant classes are:
Project
Iteration
Task
Person

with those relations:

Project has_many Iterations
Iteration has_many Tasks
Person has_many Tasks

In the project view, I can iterate through all project/iteration/task data, but I have no clue on how to access the Person data.

<table border=1 >
<% for project in @projects %>
    <tr valign="top">
        <td><%= project.id %></td>
        <td><%= project.name %></td>
        <td><%= project.description %></td>
        <td><table border=1>
            <% for iteration in project.iterations %>
            <tr valign="top">
                <td><%= iteration.name %></td>
                <td><table border=1>
                    <% for task in iteration.tasks %>
                    <tr valign="top">                       
                        <td><%= task.name %></td>
                        <td><table border=1>
                            <tr><td>
                                      Now what ?
                            </td></tr>
                            </table>
                        </td>
                    </tr>
                    <% end %>
                    </table>
                </td>
            </tr>
            <% end %>
        </table></td>
    </tr>
</table>
<% end %>

Person data is saved in a table named 'people'.
I tried to access a person object through task and directly through @people, but neither works.

Any pointers ?

Thanks.

Re: Accessing Model Data in Views

Try this:

<% for task in iteration.tasks %>
<tr valign="top">                       
    <td><%= task.name %></td>
    <td><table border=1>
        <tr><td>
          <% for person in task.people %>
            <%= person.name %>
          <% end %>
        </td></tr>
        </table>
    </td>
</tr>
<% end %>

That said, are you certain the association between person and task is correct? There are multiple people per task? How about on the reverse end, does a person have only one task or multiple tasks? Assuming it's the latter, you probably want to set up a has and belongs to many association.

Railscasts - Free Ruby on Rails Screencasts

Re: Accessing Model Data in Views

Ah, I solved it and it had indeed to do with associations.
Yes, the a association was correct: a Task has only one Person assigned to it, but one Person can have many Tasks assigned.

No, my error was to treat a single instance of a Person as an array.
So, instead of doing a for loop over Person i simply had to write

<%= task.person.username %>

and all's well.

Doh! smile