This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Rails Routing Cheatsheet

A quick reference guide for Rails routing: resourceful routes, member and collection actions, namespaces, scopes, constraints, and route helpers.

· Published

The Rails router recognizes URLs and dispatches them to a controller's action, while generating reciprocal paths and URLs through helpers.

Resourceful Routes (resources)

Rails.application.routes.draw do
  root "home#index"

  resources :articles do
    # Member routes (operates on specific item /articles/:id/publish)
    member do
      patch :publish
    end

    # Collection routes (operates on /articles/search)
    collection do
      get :search
    end

    # Nested resources (/articles/:article_id/comments)
    resources :comments, only: [:create, :destroy]
  end
end

Route Path Helpers

Action Path Helper URL Generated
index articles_path /articles
show article_path(@article) /articles/:id
new new_article_path /articles/new
edit edit_article_path(@article) /articles/:id/edit

Namespaces & Scopes

# Namespace: prefix URL with /admin and controllers with Admin::
namespace :admin do
  resources :users
end
# Routes to Admin::UsersController at /admin/users

# Scope: prefix URL without modifying controller namespace
scope "/v1" do
  resources :posts
end

Custom Singular Routes & Redirects

# Custom verb mapping
get '/about', to: 'pages#about'
post '/webhook', to: 'webhooks#receive'

# 301 Permanent Redirect
get '/stories', to: redirect('/articles')

References

Related topics