Named Routes in Rails 5


Step 1

Define the route for home page in routes.rb.

root 'projects#index'

Step 2

The tasks index page displays all the projects on the home page.

      <th colspan="3"></th>
    <% @projects.each do |project| %>
        <td><%= %></td>
        <td><%= pluralize(project.tasks.length, 'task') %></td>
    <% end %>
<%= link_to 'New Project', new_project_path %>

Step 3

The projects controller, index action looks like this:

def index
  @projects = Project.all

Step 4

Browse to http://localhost:3000 to view all projects.

Step 5


<%= projects_url %> <br>
<%= projects_path %> <br>

to the project index page. This will generate:


The URL with the domain is the absolute URL and the other is the relative URL.

Step 6

Define a named route for listing tasks in the archive page in routes.rb.

get '/tasks/:year/:month' => "tasks#archive", as: :task_archive

Step 7

View the new route.

$rake routes
task_archive GET    /tasks/:year/:month(.:format)      tasks#archive

Step 8

Use the named route in the projects index page. Add the following:

<%= task_archive_path(2007, 5) %>
<%= task_archive_path(year: 2007, month: 5) %>

to the projects index page. To view the generated URL, reload the projects index page. You will see:


in the browser.

Step 9

Define project resource in routes.rb:

resources :projects

Step 10

Add the links to the projects/index.html.erb:

<% @projects.each do |project| %>
    <td> <%= link_to, project %> </td>
    <td> <%= link_to 'Edit', edit_project_path(project) %> </td>
    <td> <%= link_to 'Destroy', project, method: :delete %> </td>
    <td><%= pluralize(project.tasks.length, 'task') %></td>
<% end %>

Now you can edit and delete projects.


In this article, you learned how to use named routes in Rails 5.


Named Routes

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.