0
0
RailsHow-ToBeginner · 3 min read

How to Use Root Route in Rails: Syntax and Examples

In Rails, you set the root route using root 'controller#action' inside the config/routes.rb file. This tells Rails which controller action to load when visiting the base URL of your app.
📐

Syntax

The root route in Rails is defined in the config/routes.rb file using the root method. It takes a string argument in the format 'controller#action', where controller is the controller name and action is the method to run.

  • root: method to set the home page route
  • 'controller#action': specifies which controller and action to call
ruby
root 'home#index'
💻

Example

This example shows how to set the root route to the index action of the home controller. When users visit the base URL, Rails will render the home#index page.

ruby
Rails.application.routes.draw do
  root 'home#index'
end
Output
Visiting http://localhost:3000/ loads the HomeController's index action view.
⚠️

Common Pitfalls

Common mistakes include:

  • Not specifying the controller and action correctly (e.g., missing quotes or wrong format).
  • Forgetting to restart the Rails server after changing routes.
  • Setting multiple root routes, which causes conflicts.
  • Using a controller or action that does not exist, leading to routing errors.
ruby
Wrong:
root home#index

Right:
root 'home#index'
📊

Quick Reference

UsageDescription
root 'controller#action'Sets the root URL to a specific controller action
root to: 'controller#action'Alternative syntax, less common but valid
Only one root routeRails allows only one root route definition
Restart server after changesNecessary to apply route changes

Key Takeaways

Use root 'controller#action' in config/routes.rb to set the home page.
Only one root route should be defined to avoid conflicts.
Always restart the Rails server after changing routes.
Ensure the specified controller and action exist to prevent errors.