How to Create Routes in Rails: Syntax and Examples
In Rails, you create routes by adding entries in the
config/routes.rb file using methods like get, post, or resources. These routes connect URLs to controller actions, defining how your app responds to web requests.Syntax
Routes in Rails are defined inside the config/routes.rb file. You use HTTP method helpers like get, post, patch, delete, or the resources method for RESTful routes.
Each route maps a URL pattern to a controller and action, for example: get '/home', to: 'pages#home' means a GET request to '/home' runs the home action in PagesController.
ruby
Rails.application.routes.draw do get '/path', to: 'controller#action' post '/path', to: 'controller#action' resources :resource_name end
Example
This example shows how to create a simple route for a home page and RESTful routes for articles.
ruby
Rails.application.routes.draw do get '/home', to: 'pages#home' resources :articles end
Output
When you visit '/home', Rails runs PagesController's home action.
The 'resources :articles' creates routes for all CRUD actions like '/articles', '/articles/:id', '/articles/new', etc.
Common Pitfalls
Common mistakes include forgetting to restart the Rails server after changing routes, using incorrect controller#action syntax, or not specifying HTTP methods properly.
Also, defining conflicting routes or placing routes in the wrong order can cause unexpected behavior.
ruby
Rails.application.routes.draw do # Wrong: missing 'to:' keyword get '/about', 'pages#about' # Correct: get '/about', to: 'pages#about' end
Quick Reference
| Route Helper | Description | Example |
|---|---|---|
| get | Defines a route for GET requests | get '/login', to: 'sessions#new' |
| post | Defines a route for POST requests | post '/login', to: 'sessions#create' |
| resources | Creates RESTful routes for a resource | resources :users |
| root | Defines the root URL | root 'pages#home' |
Key Takeaways
Define routes in config/routes.rb using HTTP method helpers or resources.
Use the correct syntax: method 'path', to: 'controller#action'.
Resources creates all standard RESTful routes automatically.
Restart the Rails server after changing routes to see updates.
Order routes carefully to avoid conflicts and unexpected matches.