How to add Custom Arguments to Links in Ruby on Rails
In this lesson we are going to create an interface between projects and tasks, giving the user an option to add another task directly from the page.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this lesson we are going to create an interface between projects and tasks, giving the user an option to add another task directly from the page.

To start with, I'm going to get the routes associated with projects and for this, I use the command:

rake routes | grep project

This will bring up all the routes associated with projects.

large

If I don't use grep, I'll have a longer list of results that will include routes of other pages like contact, about and home. In this sense, grep is a filter that displays only those routes with the word project in them. From the list, the one that we need the most for now is the second one - new_project_task.

Now, let's go to our project show page, which is show.html.erb. Here, I'm going to add a new link, pass the project_id as a parameter so that application knows to which project the new task should be added. To do this, the code would be:

<hr>
<h2>Tasks for project</h2>
<%= link_to "Add a new task for this project", new_project_task_path(project_id: @project.id) %>

large

Now, if we test it in the browser, this is what we should see.

medium

When you click on the link, it takes you to the add_task page, and more importantly, it takes you to the right project id.

large

If you see in the URL, it takes you to project 13, which is the right one.

If you don't pass the project id as a parameter, then html is not going to know which project the task should be associated with because html by itself is stateless, which means, it knows nothing about navigating from page to page unless you tell it.

So, this is how you add a link for nested resource.