The Root Route in Ruby on Rails
In Ruby on Rails Feb 2, 2022
Updated on Feb 2, 2022
When developing a web application, the most important thing is to set what to display on the home page. In Ruby on Rails, we specify what we want to show on the home page by defining a root route.
When the user visits our site, they make a request for our home page. The Rails router forwards this request to a controller action.
We can specify what controller action to run by defining a root
route. In Rails, we define our routes in
a file called routes.rb
in the config/
folder.
We put these routes inside the Rails.application.routes.draw do
block. Usually, we put the
root
route at the top, because it is the most accessed route.
We set the root
route using the root
method. How do we use this method? Let's say we have a
controller called pages
and an index
action inside this controller. We can set the
root
route to this index
action like this:
root to: 'pages#index'
Or we can use the shortcut:
root 'pagex#index'
No need to specify an HTTP
method, because in Rails the root
route always routes only
GET
requests.