In config/routes.rb, how do you send old /journal/2019/our-venue URLs to new paths with redirect(), and which status does it send by default?
answer
- a Rack endpoint, no controller
- %{name} interpolates path params
- status: option overrides
- 301 Moved Permanently by default
- braces, not do...end, for the block
basics
~10 sPoint the old route at redirect(), as in get "journal/:year/:slug", to: redirect("/stories/%{year}/%{slug}"). It answers 301 Moved Permanently unless you pass status:, and the string form drops the old query string.
solid answer
~40 s`redirect` is a routing helper that builds a small Rack endpoint, so no controller or `before_action` runs. The string form interpolates path params with `%{name}`: `get "journal/:year/:slug", to: redirect("/stories/%{year}/%{slug}")` sends `/journal/2019/our-venue` to `/stories/2019/our-venue`, escaping the values. The default status is **301 Moved Permanently**, which browsers may cache, so pass `status: 302` while you are still testing the mapping. The string form ignores the incoming query string; the options form, `redirect(path: "/stories/%{slug}")`, changes only the parts you name and keeps the query. For logic, pass a block in braces, `redirect { |params, req| ... }`, that returns a string; a `do...end` block would bind to `get` instead.
code
ruby · 14 lines# config/routes.rb
Rails.application.routes.draw do
# /journal/2019/our-venue -> /stories/2019/our-venue (301, query dropped)
get "journal/:year/:slug", to: redirect("/stories/%{year}/%{slug}")
# keeps ?ref=... because only the path changes
get "blog/:slug", to: redirect(path: "/stories/%{slug}")
# temporary while the mapping is tested
get "news/:slug", to: redirect("/stories/%{slug}", status: 302)
# braces so the block reaches redirect, not get
get "j/:id", to: redirect { |params, req| "/stories/#{params[:id].downcase}" }
endgo deeper
Recall get "old", to: redirect("/new"), the %{name} interpolation and that the default status is 301.
Explain the three forms, why the string form drops the query and why the block must use braces.
Plan a legacy URL migration: test with 302, watch the misses, switch to 301, and watch glob plus format edge cases.
Decide which legacy URLs deserve permanent mappings and for how long, weighing search ranking and old links against routes-file clutter.
## Why redirect in the router When a site changes its URL scheme, old links keep arriving from search results, emails and bookmarks. In the wedding-planner app, couples' posts used to live at `/journal/2019/our-venue` and now live at `/stories/2019/our-venue`. The cheapest place to map one onto the other is `config/routes.rb`, using the **`redirect`** helper: ```ruby get "journal/:year/:slug", to: redirect("/stories/%{year}/%{slug}") ``` `redirect` returns a tiny **Rack endpoint**, not a controller action. The router calls it directly, so no controller class is loaded, no `before_action` runs and nothing is rendered; the endpoint just answers with a `Location` header and an empty body. ## The three forms | Form | Example | What it does | |---|---|---| | String | `redirect("/stories/%{year}/%{slug}")` | Interpolates path params into a fixed template | | Options | `redirect(path: "/stories/%{slug}")` | Changes only the URL parts you name and keeps the rest | | Block or callable | `redirect { \|params, req\| ... }` | Runs Ruby and returns the target as a string | Details worth knowing for each: - **String form.** `%{year}` and `%{slug}` are replaced with the matched path params, escaped for a URL. The incoming **query string is dropped**: `/journal/2019/our-venue?ref=mail` goes to `/stories/2019/our-venue`. - **Options form.** It starts from the current request's protocol, host, port, path and query parameters and overrides only what you pass (`path:`, `host:`, `subdomain:` and so on), so `?ref=mail` survives. - **Block form.** The block receives the path params and the request and must return a string. Write it with **braces**: with `do...end`, Ruby hands the block to `get`, not to `redirect`. An object that responds to `call` with the same two arguments works too, which keeps reusable logic out of the routes file. - A target **without a leading slash** is prefixed with the app's script name, which matters when the app is mounted under a sub-path. ## Status codes The default is **301 Moved Permanently**. The `status:` option changes it: ```ruby get "journal/:year/:slug", to: redirect("/stories/%{year}/%{slug}", status: 302) ``` The routing guide warns that browsers and proxies may cache a 301, which makes a wrong mapping hard to take back. A common routine is: 1. Ship the mapping with `status: 302` and watch the logs for misses. 2. Fix any pattern that sends guests to a dead page. 3. Switch to the default 301 once the mapping is final. The status semantics themselves (which code keeps the method and body, how clients resolve `Location`) are HTTP questions; from Rails' side the point is the default and the option. ## Globs for deep legacy paths If the old URLs had a variable depth, such as `/journal/2019/06/our-venue`, a **glob segment** captures the rest of the path: ```ruby get "journal/*rest", to: redirect("/stories/%{rest}") ``` `params[:rest]` becomes `2019/06/our-venue`, and interpolation keeps the slashes. One subtlety: by default a trailing extension is split off into the optional format, so `/journal/2019/our-venue.html` interpolates `rest` as `2019/our-venue` and the `.html` disappears from the target. Add `format: false` to the route if the extension must travel. ## Where it shows up and what to check - `bin/rails routes` lists the endpoint as `redirect(301, /stories/%{year}/%{slug})`, so the status is visible in the route table. - Redirect routes match like any other route: they need the right verb (`get`), they obey constraints, and their position in the file matters. - Keep targets **internal**. A block that builds the target from request data can become an open redirect; that is a security topic of its own. - When the mapping needs the database (an old numeric id to a new slug), use a block or callable sparingly, or a controller action that can look the record up and render a 404 when it is gone. ## Pinning the mapping in a test A redirect route has no controller to unit-test, so the check is an integration test that requests the old URL and asserts where it lands: ```ruby test "old journal URLs move to stories" do get "/journal/2019/our-venue" assert_response :moved_permanently assert_redirected_to "/stories/2019/our-venue" end ``` One such test per legacy pattern catches the two classic regressions: a status that slipped back to the wrong code, and a later route edit that changed the interpolated path. Used this way, `redirect` keeps old links alive with one line per pattern, without a controller in the way.
- Why does redirect do |params, req| ... end inside a get line in config/routes.rb not behave as expected?Ruby binds a `do...end` block to the outermost method call, which is `get`, not `redirect`. `redirect` then receives no block and no path, and Rails raises an error that the redirection argument is not supported. Use braces, `redirect { |params, req| ... }`, which bind to the nearest call, or pass an object that responds to `call`.
- In a Rails redirect route, how do you keep the incoming query string?Use the options form, such as `redirect(path: "/stories/%{slug}")`. It starts from the current request's protocol, host, port, path and query parameters and replaces only what you pass, so `?ref=mail` survives. The plain string form builds the target from the template alone and drops the query.
A redirect route is a forwarding sticker on an old mailbox: the post office reads it and sends the letter on without anyone opening the house, and a permanent sticker is one the neighbours memorise.
- redirect() in routes calls a controller action, so before_action filters run first
- Rails' routing redirect defaults to 302 Found
- The string form of redirect() always forwards the original query string
- A do...end block works the same as braces for redirect inside a get line
- redirect() routes skip constraints and the HTTP verb check