- Read Tutorial
- Watch Guide Video
In this lesson, we are going to see how we can list the tasks
associated with each project in the show
page.
Technically speaking, you can insert this code in show.html.erb
and this would work.
However, it is one of the antipatterns in Rails as you cannot have logic in views files. So, you have to control it either from the model or from the controller.
So, open projects_controller.rb
and go to the show
method.
def show @tasks = @project.tasks end
What I'm doing here is getting all the tasks associated with that particular project and storing them in an instance variable called tasks
.
Once this is done, let's go back to our show.html.erb
and call this instance. To do this, add this line
<% @tasks.each do |task|%> <p> <%= link_to task.title, project_task_path(@project.id, task.id)%> </p> <% end %>
In this code, I'm creating a link to the title of each task, and directing it to the project_task_path
link that takes project.id
and task.id
as its parameters. If you're unsure of the path, go to the console and type
rake routes | grep task
and this will bring up all the routes that has the word task
in it.
From here, take the associated route for viewing tasks.
This is the code
To check if this works, let's start the server and refresh the browser. This is what you can see:
And it's working fine. If you click on each of the links, it will take you to the show page. For now, this page is empty and in the next lesson, we'll see how to add information to this page.