0
0
Ruby on Railsframework~5 mins

Root route in Ruby on Rails

Choose your learning style9 modes available
Introduction

The root route tells your Rails app what page to show first when someone visits your website's main address.

When you want to set the homepage of your website.
When you want visitors to see a welcome or dashboard page first.
When you want to direct users to a landing page after login.
When you want to organize navigation starting from a main page.
When you want to avoid errors from no default page set.
Syntax
Ruby on Rails
root 'controller_name#action_name'

Replace controller_name with your controller's name (usually plural).

Replace action_name with the method that renders the page (like index or home).

Examples
This sets the homepage to the index action in the WelcomeController.
Ruby on Rails
root 'welcome#index'
This sets the homepage to the home action in the DashboardController.
Ruby on Rails
root 'dashboard#home'
Sample Program

This example sets the root route to the home action in PagesController. When you visit the main URL, it shows a plain text welcome message.

Ruby on Rails
# config/routes.rb
Rails.application.routes.draw do
  root 'pages#home'
end

# app/controllers/pages_controller.rb
class PagesController < ApplicationController
  def home
    render plain: "Welcome to the Home Page!"
  end
end
OutputSuccess
Important Notes

Only one root route should be set in your routes file.

If you don't set a root route, visiting the main URL will cause an error.

You can check your root route by running rails routes in the terminal.

Summary

The root route sets the default page for your website.

It uses the syntax root 'controller#action'.

Setting a root route helps visitors see a starting page without errors.