Root Routes Setting the Root Page of the App

In this demonstration, I will show how to set an existing webpage as the root webpage of a web app. The root webpage is the one that displays for requests that include only the domain/port part of the URL and not the resource path (e.g., http://localhost:3000/). The root webpage is often thought of as the default page for the web app.

General Steps

In general, there is only one step for setting an existing webpage as the root webpage.

Set the Home Page as the Root Webpage of the Billy Books App

To demonstrate the steps for setting an existing webpage as the root webpage, we will be setting the home page of the Billy Books bookstore base app as the root webpage for the app.

Base App Code

Step 1 Add a Root Route

To set the home page as the root webpage for the app, we add a root route to the routes in config/routes.rb, like this:

Rails.application.routes.draw do

  root to: redirect('/home')

  get 'home', to: 'pages#home', as: 'home'
  get 'about', to: 'pages#about', as: 'about'

end

Note that the root route accepts a to: argument that specifies how the web server should respond to HTTP GET requests that match the root route. In the above code, the to: argument calls the redirect route helper method, which causes the browser to be sent an HTTP redirect response, telling it to request a different webpage—the home page in this case.

Test It!

To confirm that we made this change correctly, we run the web app (as per the steps in the running apps demo), and we open the URL http://localhost:3000/ in our web browser. The URL in the browser’s location bar should automatically change to http://localhost:3000/home, and the Billy Books home page should be displayed.

Step 1 Changeset

Conclusion

Following the above steps, we have now added a root route for the Billy Books bookstore app so that requests for the root URL for the app (e.g., https://localhost:3000) will automatically be redirected to the app’s home page.

Demo App Code