Routing in Rails
Routing is the bridge between incoming HTTP requests and the code that handles them. When a user visits a URL in your Rails application, the router determines which controller and action should process the request based on the URL path and HTTP method. Understanding routing is essential for building any Rails application.
In this guide, you’ll learn how Rails routing works, how to define RESTful routes, and how to customize routing for your application’s needs.
How Rails Routing Works
Every Rails application has a routes file located at config/routes.rb. This file defines all the URLs in your application and maps them to controller actions. When a request comes in, Rails reads this file from top to bottom and matches the first route that satisfies the request.
The router parses the URL path and extracts any dynamic segments. It then dispatches the request to the appropriate controller action, passing any captured parameters as arguments.
Consider a basic Rails application without any routes defined. If you try to visit any page, you’ll see a routing error. You must explicitly define routes for your application to respond to requests.
RESTful Routing
Rails follows the REST architectural pattern by default. RESTful routing maps HTTP methods and URLs to CRUD (Create, Read, Update, Delete) operations on resources. The resources method generates seven standard routes for a resource.
# config/routes.rb
Rails.application.routes.draw do
resources :articles
end
This single line creates seven routes:
| Method | Path | Controller#Action | Purpose |
|---|---|---|---|
| GET | /articles | articles#index | List all articles |
| GET | /articles/new | articles#new | Show new article form |
| POST | /articles | articles#create | Create new article |
| GET | /articles/:id | articles#show | Show specific article |
| GET | /articles/:id/edit | articles#edit | Show edit form |
| PATCH/PUT | /articles/:id | articles#update | Update article |
| DELETE | /articles/:id | articles#destroy | Delete article |
The :id is a dynamic segment—you can access it in your controller using params[:id].
You can verify your routes using the terminal command:
rails routes
This displays all defined routes with their path prefixes, HTTP methods, and controller actions. Adding -c ArticlesController filters to show only routes for that controller.
Custom Routes
Sometimes you need routes beyond the standard RESTful pattern. Rails allows you to define custom routes for specific actions.
Route Helpers
Custom routes use the get, post, patch, put, and delete methods:
Rails.application.routes.draw do
# Simple path
get '/about', to: 'pages#about'
# With a root route
root 'articles#index'
# Custom action on a resource
resources :articles do
member do
get :publish
end
collection do
get :archived
end
end
end
The member block creates routes that operate on a single resource (they include the resource’s ID), while collection block creates routes that operate on the entire collection.
With this configuration, you get additional routes like /articles/:id/publish and /articles/archived. Rails generates helper methods like publish_article_path(@article) and archived_articles_path for these routes.
Route Constraints
Route constraints let you restrict which requests match a route based on conditions. This is useful for subdomain routing, format restrictions, or custom logic.
Rails.application.routes.draw do
# Subdomain constraint
constraints(subdomain: 'admin') do
get '/', to: 'admin#dashboard'
end
# Format constraint
get '/articles', to: 'articles#index', constraints: { format: 'json' }
# IP address constraint
constraints(ip: /192\.168\.\d+\.\d+/) do
get '/debug', to: 'debug#info'
end
# Custom constraint class
constraints(DeviseConstraint) do
get '/dashboard', to: 'dashboard#show'
end
end
You can also use constraints on route parameters to validate input:
get '/users/:id', to: 'users#show', constraints: { id: /\d+/ }
This route only matches when :id contains only digits, preventing matches for non-numeric IDs.
Named Routes
Named routes generate helper methods with custom names, making your code more readable. Instead of typing complex paths, you use descriptive method names.
Rails.application.routes.draw do
get '/help', to: 'pages#help', as: 'help'
get '/privacy', to: 'pages#privacy', as: 'privacy_policy'
resources :articles do
get :preview, on: :member, as: :preview
end
end
This generates helpers like help_path, privacy_policy_path, and preview_article_path(@article). You can also use the _url variant for the full URL including the domain.
In your views and controllers:
<%= link_to 'Help', help_path %>
<%= link_to 'Privacy Policy', privacy_policy_url %>
<%= link_to 'Preview', preview_article_path(@article) %>
Route Globbing and Redirects
Route globbing captures multiple path segments into a single parameter:
get '/files/*path', to: 'files#show'
A request to /files/documents/reports/budget.pdf sets params[:path] to documents/reports/budget.pdf.
You can also create redirects directly in your routes:
Rails.application.routes.draw do
get '/old-page', to: redirect('/new-page')
get '/docs/:section', to: redirect { |params, request| "/guides/#{params[:section]}" }
get '/legacy', to: redirect('https://legacy.example.com', status: 301)
end
Redirects are useful for maintaining backward compatibility when you change your URL structure.
When to Use RESTful vs Custom Routes
RESTful routes work well for resource-based features that follow the Create-Read-Update-Delete pattern. They provide a consistent interface that other developers understand, and they integrate with Rails conventions and helpers.
Custom routes are appropriate for non-resource features like search, authentication callbacks, or one-off pages. Use custom routes when REST doesn’t fit your use case, but avoid overusing them—too many custom routes can make your application harder to understand.
Summary
Rails routing maps incoming HTTP requests to controller actions. The resources method generates RESTful routes automatically. Custom routes with get, post, and other HTTP verb methods handle non-standard URLs. Route constraints let you restrict matching based on subdomains, formats, or custom logic. Named routes create helpful helper methods for your views and controllers.
Understanding routing is foundational to Rails development. The routes file is the entry point for your application’s URL structure—spend time designing it thoughtfully.