Named Routes in Rails 5

Steps

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.

<h1>Projects</h1>
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Count</th>
      <th colspan="3"></th>
    </tr>
  </thead>
  <tbody>
    <% @projects.each do |project| %>
      <tr>
        <td><%= project.name %></td>
        <td><%= pluralize(project.tasks.length, 'task') %></td>
      </tr>
    <% end %>
  </tbody>
</table>
<%= link_to 'New Project', new_project_path %>

Step 3

The projects controller, index action looks like this:

def index
  @projects = Project.all
end

Step 4

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

Step 5

Add:

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

to the project index page. This will generate:

http://localhost:3000/projects 
/projects

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:

/tasks/2007/5
/tasks/2007/5

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| %>
  <tr>
    <td> <%= link_to project.name, 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>
  </tr>
<% end %>

Now you can edit and delete projects.

Summary

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

Reference

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.