How to Add a root Route in Rails

How to Add a root Route in Rails

July 09, 2024

This post shows how to configure a root route for your application. This is the page your visitors will encounter the first time they visit your Rails app.

This post is part of my handbook on the Rails Router.

Your application's home page is one of the most important and highly trafficked page. This is the page many visitors will encounter the first time they visit your application.

The root helper method configures the home page of your Rails app.

Rails.application.routes.draw do
# Defines the root path route ("/")
root "application#home"
end

The root indicates the application URL '/', without any path, such as /users.

The router parses the routes top-down and stops search as soon as it finds a matching route. Hence, it's recommended that you should put the root route at the top of the routes file. It is the most popular route which should be matched first.

Since most visitors will be visiting the application by making a GET request to your application URL, the root route only handles and routes HTTP GET requests.

You can also use the root helper inside a namespaces and scope.

namespace :admin do
root to: "admin#index"
end

root to: "home#index"

If you don't provide the root route, Rails routes the request to the home page to an internal controller Rails::WelcomeController which renders the welcome page.

Rails welcome page


Sign up for my newsletter

Let's learn to become better developers.

Comments

No comments yet. Be the first to leave one.

Sign in to leave a comment.