Rails Routing: RESTful, Custom, and Named Routes
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.
Rails routing gives you a single file, config/routes.rb, that defines every URL your application responds to. This guide covers how RESTful routes work, how to add custom routes when you need them, and how to name your routes so views and controllers stay readable.
intro context
If you are learning Rails routing for the first time, it helps to think in terms of recognition rather than magic. The router is just a lookup table that says, “when this path and verb arrive, send them here.” Once that idea clicks, the routes file stops feeling mysterious and starts feeling like the public map of your application.
Rails routing also gives you a shared vocabulary with the rest of the framework. Controllers, views, and models all depend on the paths you define here, so a small routing decision can affect how forms submit, how links are named, and how requests are organized across the app. That is why the routing file is one of the first places to check when a page behaves unexpectedly.
For broader context, see the Rails getting started tutorial and the Rails MVC pattern tutorial.
tl;dr
Rails routing decides which controller action handles each request. Use resources for standard CRUD pages, add custom routes when a URL does not map cleanly to a resource, and keep helper names readable so views stay easy to follow. The best routes files are explicit, small, and organized around the URLs your users actually see.
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. The output is especially useful after adding nested resources or custom routes, because it confirms the helper names and URL patterns Rails generated before you wire them into views and controllers.
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. Member routes always include the resource ID in the path, while collection routes apply to the resource as a whole, which keeps the URL structure predictable as the app grows.
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, which is the most common use case in practice. A regex constraint on :id ensures that only numeric values reach the controller:
get '/users/:id', to: 'users#show', constraints: { id: /\d+/ }
This route only matches when :id contains only digits, preventing matches for non-numeric IDs. Parameter constraints act as a first line of defense: a malformed request fails at the routing layer before it ever reaches your controller, which keeps the controller code focused on the happy path.
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. Named routes decouple the URL structure from the views, so you can reorganize paths without updating every template that links to a page.
In your views and controllers:
<%= link_to 'Help', help_path %>
<%= link_to 'Privacy Policy', privacy_policy_url %>
<%= link_to 'Preview', preview_article_path(@article) %>
Named helpers make the view code read like English rather than a URL map. When you rename a route later, you only change the routes file; every view that uses the helper updates automatically because the helper name stays the same.
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. Globbing is useful for catch-all routes and file-serving endpoints where you need to capture a variable depth of path segments in one parameter.
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. A 301 redirect also preserves your search engine ranking for the old URL, which makes it a better choice than simply removing a route and returning a 404. Redirects in the routes file also keep the URL migration logic in one place instead of scattering it across multiple controllers.
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.
When a route feels unclear, ask whether the URL describes a resource or an action. Resources usually belong in resources, while actions like search, preview, or archive often fit better as custom routes. That small decision keeps the routes file readable and helps the rest of the team guess the right helper method without hunting through the file.
common routing mistakes
One common mistake is adding custom routes before the more general resource routes without thinking through precedence. Rails matches top to bottom, so a narrow route placed too late may never run. Another mistake is using custom routes for every action just because it feels faster at the moment. That usually leaves the file harder to scan later.
It also helps to keep route names predictable. If a helper name is confusing, ask whether the action belongs on a resource or should be renamed to reflect the work it performs. The clearer the helper, the less time you spend tracing links back to the routes file during debugging.
forward link
Once routing feels natural, move on to the Rails MVC pattern tutorial to see where the router sends the request after it matches a path. The Rails migrations tutorial is also useful because it shows how the model layer gets its structure before routing ever hands it a request. Those two guides make routing easier to remember because they connect URLs to the rest of the stack.
If you want to keep building on the same mental model, the Rails views and partials tutorial shows how those routed requests become HTML responses. That closes the loop from request to route to rendered page.
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, and the best routing files usually stay small, explicit, and easy to scan.
For more detail, read the official Rails routing guide. It explains how the router behaves in edge cases and how route precedence works when multiple patterns could match the same request.
See Also
- Rails MVC Pattern — How the router connects to controllers and views
- Rails Getting Started — Full walkthrough of a Rails app from routing to deployment
- Rails Migrations — Database structure that backs your routed resources