How to Add a Root Route in Ruby on Rails

09/19/2021

Contents

In this article, you will learn how to add a root route in Ruby on Rails.

Adding a root route

To add a root route in Ruby on Rails, you will need to make some changes to the routes.rb file in your Rails application. Follow these steps:

  • Open the config/routes.rb file in your Rails application.
  • Locate the line that says Rails.application.routes.draw do and add a new line below it.
  • On the new line, add the following code:

    root 'controller_name#action_name'

    Replace controller_name with the name of the controller you want to use for the root route, and action_name with the name of the action you want to use for the root route. For example, if you want to use the pages controller and the home action, the code would look like this:

    root 'pages#home'
  • Save the routes.rb file.
  • Restart your Rails server to make sure the changes take effect.

Now when you visit the root URL of your Rails application, it will load the controller and action specified in the root route.