Guide to Nested Routes in Rails
In this lesson, we are going to talk about customizing routes and creating nested routes.
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 talk about customizing routes and creating nested routes.

To start, go to the config/routes.rb file.

Remove the three routes at the top, and replace them with this code:

resources :tasks, except: [:index]

This will leverage the resources method in Rails, which will bring in all of the CRUD functionality we're looking for, and in this case we're saying that we don't want the index action to be supplied.

Now, we are going to try nested routes. In this application, let's say I have Project A and three tasks namely Task 1, Task 2 and Task 3 associated with it. Since the projects and tasks are tied together in the database, a task cannot exist as a standalone entity. In other words, a task should always be a part of a project, and not exist separately.

In the above code, my tasks page would be displayed as .com/tasks/1. However, if you'd like to know what project that particular task belongs to, then it makes sense to have a URL like this: .com/projects/5/tasks/2. This would clearly mean the second task of the fifth project. To do this, I'm going to remove the projects resources code, and instead write a code block nested inside of the projects resource.

resources :projects do
  resources :tasks, except: [:index], controller: 'projects/tasks'
end

So your routes file should look like this:

large

Before executing this code, go to your controllers folder and create a new folder inside it called projects. Now, move tasks_controller.rb to this projects folder. This way, tasks is not at the root of the application, rather it is nested inside the projects folder, and this is just what we want. Next, do the same thing for your views too.