How can I show the name of a belongs_to model on my Index page in rails?
I have two models in Rails. A task and a status. I have put the relationships in the models correctly. A task belongs to a status and a status has_many tasks. So far so good.
However when showing all my tasks on the index page (see my index.html.erb
below) I cannot show the status field correctly.
What should I put in my tasks controller and what code should I put in my index.html.erb
file below?
The status model only has a name in it and each task has a foreign key status_id in the database. The statusses are for instance "Open" and "Closed". I cannot get these statusses shown on my index page of all the tasks.
Thanks.
<h1>Listing tasks</h1>
<table>
<tr>
<th>Activity</th>
<th>List</th>
<th>Context</th>
<th>Descripton</th>
<th>Project</th>
<th>Deadline</th>
<th>Owner</th>
<th>Delegated to</th>
<th>Status</th>
<th>Estimated hours</th>
<th>Remaining hours</th>
<th>Closed on</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @tasks.each do |task| %>
<tr>
<td><%= task.activity %></td>
<td><%= task.list%></td>
<td><%= task.descripton %></td>
<td><%= task.project %></td>
<td><%= task.deadline %></td>
<td><%= task.owner %></td>
<td><%= task.delegated_to %></td>
<td><%= @status.name %></td> ?????????? Here I want to put my status name f.i. "Open" of that task.
<td><%= task.estimated_hours %></td>
<td><%= task.remaining_hours %></td>
<td><%= task.closed_on %></td>开发者_如何学JAVA
<td><%= link_to 'Show', task %></td>
<td><%= link_to 'Edit', edit_task_path(task) %></td>
<td><%= link_to 'Destroy', task, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Task', new_task_path %>
I am going to take a guess, because like the first commenter I found the post extremely difficult to read.
So if you have a Task and Status and they are setup correctly then you can access the status by simply using:
task.status.name
Now in your controller you will want to include the Status. This can be done very easily.
Task.find(:all, :include => :status)
You will want to make sure to add an index to your database on tasks.status_id.
Hope this helps =)
Well, you should be able to get at it as simply as:
<%= task.status.name %>
精彩评论