In config/routes.rb, how do root, get with to: "stories#preview" and match with via: map one-off URLs, and how are those routes named?
answer
- "controller#action" string
- root is GET / named root
- verb methods: get, post, patch
- match demands via:
- as: names dynamic paths
basics
~10 sroot "stories#index" maps GET / and defines root_path; get "stories/:id/preview", to: "stories#preview", as: :preview_story maps one verb and path to an action; match does the same for several verbs and raises ArgumentError without via:.
solid answer
~40 sOutside resources, routes map one verb and path to a `controller#action` string. `root "stories#index"` (or `root to: "stories#index"`) answers `GET /` and defines `root_path`. `get "stories/:id/preview", to: "stories#preview"` maps a GET with a dynamic `:id` segment; `post`, `patch`, `put` and `delete` work the same, and `get "up" => "rails/health#show"` is the hash form the generated routes file uses. A static path such as `get "about", to: "pages#about"` is named after its path (`about_path`), but a path with a dynamic segment gets no name, so pass `as: :preview_story` for `preview_story_path(story)`. `match` takes `via: [:get, :post]` or `via: :all`; without `via:` it raises `ArgumentError`, because Rails wants every route's verbs chosen deliberately.
code
ruby · 13 lines# config/routes.rb
Rails.application.routes.draw do
root "stories#index"
get "about", to: "pages#about"
get "stories/:id/preview", to: "stories#preview", as: :preview_story
match "stories/:id/print", to: "stories#print", via: [:get, :post]
end
# root_path # => "/"
# about_path # => "/about"
# preview_story_path(story) # => "/stories/42/preview"go deeper
Write root, get with to: "controller#action" and as:, and know that root defines root_path and that match needs via:.
Explain how one-off routes are named, why a dynamic path needs as:, and why Rails forces a via: choice on match.
Keep one-off routes for pages that are not records, and move growing clusters of them into member, collection or resource routes.
Hold the line that every route's verbs are chosen deliberately, since the route table is the app's public surface.
## Routes that are not resources Most of a newsroom CMS's routes come from `resources`, but a few URLs stand alone: the home page, an "about" page, a print preview of a story. Rails' routing DSL in `config/routes.rb` maps each of these with one line that names an HTTP verb, a path and a target. ## root ```ruby root "stories#index" # same as: root to: "stories#index" ``` - `root` answers **`GET /`** and dispatches to `StoriesController#index`. - It defines the **`root_path`** and `root_url` helpers. - A new app's generated `config/routes.rb` contains it **commented out** (`# root "posts#index"`), so in development a fresh app shows the Rails welcome page until you add one. - Inside a namespace it becomes that section's home: `namespace :admin do root "dashboard#show" end` answers `GET /admin` with `admin_root_path`. ## get, post and the other verb methods ```ruby get "about", to: "pages#about" get "stories/:id/preview", to: "stories#preview", as: :preview_story ``` - The method name is the **HTTP verb**: `get`, `post`, `patch`, `put`, `delete`. - `to:` takes a **`"controller#action"` string**: `"stories#preview"` means `StoriesController#preview`. A nested controller is written with a slash, `"admin/stories#index"`. - The **hash form** `get "up" => "rails/health#show"` means the same thing; the generated routes file uses it for the health check. - **Dynamic segments** such as `:id` match one path segment and arrive in `params`, so `/stories/42/preview` gives `params[:id] == "42"`. ## How such routes are named Helpers come from route names, and for one-off routes the name depends on the path: 1. A **static path** gets a name derived from it: `get "about"` defines `about_path`; `get "desk/inbox"` defines `desk_inbox_path`. 2. A path with a **dynamic segment** gets **no name**, because `:id` cannot be part of a Ruby method name. Without `as:`, no helper exists. 3. **`as:`** sets the name explicitly: `as: :preview_story` defines `preview_story_path(story)` and `preview_story_url(story)`. ## match and via: `match` is the general form behind the verb methods. It **requires** `via:`: ```ruby match "stories/:id/preview", to: "stories#preview", via: [:get, :post] match "webhooks/wire", to: "wire_webhooks#create", via: :all ``` Without `via:`, `match` raises `ArgumentError` when the routes load, with a message suggesting `via: [:get, :post]` or `get`. Rails insists because a route that silently answers every verb lets a state-changing action be triggered by a plain `GET`, which links, prefetchers and crawlers send freely. `via: :all` is still available for the rare endpoint that genuinely must accept anything, such as a mounted app or a webhook receiver you do not control. ## Common slips | Slip | What happens | |---|---| | `get "stories/:id/preview"` with no `to:` | No controller can be inferred from a path with a dynamic segment: `ArgumentError` ("Missing :controller key") when routes load | | `match "preview", to: "stories#preview"` with no `via:` | `ArgumentError` when the routes load | | Expecting `preview_story_path` without `as:` | `NameError`: the dynamic path produced no name | | `get "stories/drafts", ...` after `resources :stories` | `show` already matches `/stories/drafts` first | ## The shorthand forms A few shortcuts appear in real routes files and interviews: - `get "pages/about"` with no `to:` infers `pages#about` from a static two-part path, and names the route `pages_about`. - `controller:` and `action:` options can replace `to:`: `get "about", controller: "pages", action: "about"`. - A `scope controller: :pages do ... end` block lets each line name only its action. These are legal but less explicit; most teams write `to: "controller#action"` so every line can be read on its own. ## Where these routes fit One-off routes are the right tool for pages that are not records (home, about, a health check) and for small additions that do not belong to a resource. When several one-off routes start acting on the same record, it is usually time to move them into a member or collection route, or into a resource of their own.
- Why does Rails refuse match "preview", to: "stories#preview" without via:?A route that accepts every verb exposes actions to `GET` requests that links, prefetchers and crawlers send without the user meaning to act. Rails raises `ArgumentError` until you choose: `via: [:get, :post]`, `via: :all`, or simply `get` or `post`. The message spells those options out.
- What helper does namespace :admin do root "dashboard#show" end define?`admin_root_path`, building `/admin`. The namespace prefixes the route name and the path, and its module makes the target `Admin::DashboardController#show`. It does not replace the app's own `root_path`, which still points at `/`.
- match without via: answers every HTTP verb by default
- Every get route gets a helper named after its path, dynamic segments included
- root "stories#index" answers any verb on /
- to: "stories#preview" calls a StoryController class
- A new Rails app's routes file already sets a root route