Routing
Routing is the only file that describes an application’s entire public surface. Reading config/routes.rb should tell you what the app does and what it accepts. Routes that are hard to read are usually routes that are hard to secure.
The 60-second answer
Section titled “The 60-second answer”“resources :posts generates seven routes mapping verb and path to a controller action. Each gets a named helper — posts_path, new_post_path, post_path(post), edit_post_path(post). Nesting expresses ownership: resources :posts do resources :comments end gives /posts/:post_id/comments, and shallow: true drops the parent segment for member routes. Namespaces add a path prefix, a module and a helper prefix at once; scope adds only what you ask for. Constraints reject requests before a controller is instantiated. Narrow every resource with only:/except: — a route you do not need is an endpoint someone can POST to.”
The seven RESTful routes
Section titled “The seven RESTful routes”| Helper | Verb | Path | Action |
|---|---|---|---|
posts_path |
GET | /posts |
index |
new_post_path |
GET | /posts/new |
new |
posts_path |
POST | /posts |
create |
post_path(post) |
GET | /posts/:id |
show |
edit_post_path(post) |
GET | /posts/:id/edit |
edit |
post_path(post) |
PATCH/PUT | /posts/:id |
update |
post_path(post) |
DELETE | /posts/:id |
destroy |
Prefer a new resource over a custom action: POST /posts/:id/publication handled by PublicationsController#create is easier to authorise than posts#publish.
Nesting and shallow routes
Section titled “Nesting and shallow routes”resources :posts do resources :comments, shallow: trueendGET /posts/:post_id/comments comments#indexPOST /posts/:post_id/comments comments#createGET /comments/:id comments#showPATCH /comments/:id comments#updateDELETE /comments/:id comments#destroyNest one level only. Three ids to identify a row that already has its own id is a sign to shallow or to scope by the immediate parent. shallow: true also works as a shallow do ... end block around several resources.
Namespaces and scopes
Section titled “Namespaces and scopes”namespace :admin do resources :users # /admin/users → Admin::UsersController, admin_users_pathend
scope module: "admin" do resources :users # /users → Admin::UsersControllerend
scope "/admin" do resources :users # /admin/users → UsersControllerendnamespace sets path prefix, module and helper prefix together. scope sets only what you pass — which is how you get an admin path without an admin controller module, or vice versa.
namespace :api do namespace :v1 do resources :posts, only: [:index, :show] endendOr version via headers and keep one controller, with a constraint.
Constraints
Section titled “Constraints”get "/posts/:id", to: "posts#show", constraints: { id: /\d+/ }
class ApiConstraint def self.matches?(request) request.headers["Accept"]&.include?("application/json") endend
constraints ApiConstraint do resources :posts, only: [:index]end
constraints subdomain: "api" do resources :posts, only: [:index]endConstraints run before the controller, so a rejected request never allocates one. Also available: defaults: { format: :json }, constraints(host: ...), and request.format.
Helpers
Section titled “Helpers”post_path(post) # "/posts/42"post_url(post) # "https://example.com/posts/42" — use in emailsposts_path(page: 2) # "/posts?page=2"
url_for(post) # post_url for a persisted record, new_post_path for Post.newredirect_to [post, comment] # post_comment_path(post, comment)Use helpers, never string paths: a hardcoded "/posts/#{post.id}" survives a route change as a bug. url_for and redirect_to accept anything implementing to_model, which is how decorators stay route-agnostic.
Follow-up questions
Section titled “Follow-up questions”- What is the difference between
namespace,scope module:andscope path:? - Why is
shallow: trueusually better than deep nesting? - How do
memberandcollectionroutes differ in the helper they generate? - What does a routing constraint run before, and why is that a performance win?
- How would you handle a
PATCHthat some clients send asPUT?
Common traps
Section titled “Common traps”- Catch-all routes.
get "*path", to: "pages#show"swallows 404s and makes missing pages look like server errors. matchwithoutvia:. Accepts every verb, including ones you never intended.- Deep nesting. Three levels means a helper with three arguments, which nobody remembers.
- Forgetting
only:. Every unused route is an endpoint someone can POST to. - Defining
roottwice. The last one wins, silently. - Hardcoded paths in views. They survive refactors as bugs.