In a Rails controller, how do you set each request's locale from params[:locale] or a (:locale) route scope, and why use I18n.with_locale in an around_action?
answer
- one concern in ApplicationController
- around_action :switch_locale
- params[:locale] from query or path
- check with I18n.locale_available?
- with_locale restores in an ensure
basics
~10 sAdd around_action :switch_locale to ApplicationController, take params[:locale] (filled by ?locale= or a (:locale) path scope) when I18n.locale_available? accepts it, else default_locale, and run I18n.with_locale(locale, &action), which restores the previous locale afterwards.
solid answer
~40 sThe idiom is a concern included in `ApplicationController` that declares `around_action :switch_locale`. The method reads `params[:locale]`, which Rails fills from a query string (`/tours?locale=fr`) or from an optional path segment declared with `scope "(:locale)", locale: /en|fr|de/` in `config/routes.rb`; checks it with `I18n.locale_available?`; falls back to `I18n.default_locale`; and runs the action with `I18n.with_locale(locale, &action)`. `with_locale` sets the locale, yields, and restores the previous value in an `ensure`, so the action, its rendering and its redirect all see one locale and nothing is left on the thread, even when the action raises. Assigning `I18n.locale =` in a `before_action` sets state that outlives the request on that server thread. Generated links keep the locale through `default_url_options`.
code
ruby · 14 linesclass ApplicationController < ActionController::Base
around_action :switch_locale
private
def switch_locale(&action)
locale = params[:locale]
locale = I18n.default_locale unless I18n.locale_available?(locale)
I18n.with_locale(locale, &action)
end
def default_url_options
{ locale: I18n.locale }
end
endgo deeper
Recall the around_action that wraps the action in I18n.with_locale and the params[:locale] source.
Explain why with_locale restores state, why the locale must be validated against available_locales, and how a (:locale) scope fills params.
Show how you cover error pages, language switchers and handed-off work, and how you order URL, preference and header sources.
Weigh path, subdomain and preference strategies for discoverability, caching and shared links across the product's locales.
## The pattern Rails does not pick a locale per request on its own; every request starts in whatever locale its thread currently holds, normally `I18n.default_locale`. The standard place to choose one is a controller callback that wraps the whole action. ```ruby # app/controllers/concerns/localized.rb module Localized extend ActiveSupport::Concern included do around_action :switch_locale end private def switch_locale(&action) locale = params[:locale] locale = I18n.default_locale unless I18n.locale_available?(locale) I18n.with_locale(locale, &action) end end ``` `include Localized` in `ApplicationController` covers every controller that inherits from it. ## Where `params[:locale]` comes from | Source | Example URL | How it reaches `params` | |---|---|---| | Query string | `/tours?locale=fr` | any route; Rails parses the query | | Optional path scope | `/fr/tours` and `/tours` | `scope "(:locale)", locale: /en\|fr\|de/` around the routes | | Required path scope | `/fr/tours` only | `scope "/:locale"`; a URL without a locale does not match | With the constrained optional scope, `/it/tours` does not match the scoped routes at all, so it ends in a routing error (a 404 page in production) before any controller runs. A query parameter has no such guard: `?locale=it` reaches the controller and must be validated there. To keep the locale in links, the app overrides `default_url_options` to return `{ locale: I18n.locale }`; route helpers then add it to every generated path. The root path needs its own `get "/:locale" => ...` mapping, since `root` ignores the scope. ## Why validate before switching `I18n.enforce_available_locales` is true by default. Passing an unchecked `"it"` or a junk string to `with_locale` raises `I18n::InvalidLocale`, which turns a mistyped or malicious URL into a 500. `I18n.locale_available?` accepts strings and symbols and returns false for `nil` and unknown values, so one check covers missing and invalid input. ## Why `with_locale` in an `around_action` 1. **It wraps everything the action does.** An `around_action` yields to the action, so the locale is set during rendering, redirects, flash messages and anything else in that block, not only in the action body. 2. **It cleans up.** `I18n.with_locale` saves the current locale, assigns the new one, yields, and restores the saved value in an `ensure`. A raised exception still restores it. 3. **It cannot leak.** `I18n.locale` is per-thread state, and Puma serves many requests on each thread. A `before_action` that only assigns `I18n.locale =` leaves the value behind for the next request on that thread whose controller does not set one. 4. **It drives template lookup too.** The controller's lookup context follows `I18n.locale`, so `show.fr.html.erb` is preferred over `show.html.erb` while the block runs. `with_locale(nil)` simply yields without changing anything, which is why the snippet resolves a concrete default instead of passing `params[:locale]` straight through. ## Things that run outside the block - **`rescue_from` handlers** run after the around callback has unwound, so an error page they render uses the restored locale, not the request's. Re-apply the locale inside the handler if error pages must be translated. - **Work handed off** to Active Job keeps the locale because the job records it at enqueue time; plain threads you start yourself do not get that treatment. ## Testing the switch An integration test can check both the chosen language and the cleanup: ```ruby test "French tour page" do get tour_path(tours(:old_town), locale: :fr) assert_select "h1", "Vieille ville" assert_equal :en, I18n.locale # restored after the request end ``` The last assertion only holds because `with_locale` restores the value; with plain assignment the test thread would still hold `:fr`. Rails' own mailer-preview controller uses the same `around_action` with `I18n.with_locale`, which is a useful reference when someone asks whether the pattern is idiomatic. ## Choosing among sources A tourism site usually combines sources in a fixed order: an explicit locale in the URL first, a signed-in visitor's saved preference next, the browser's language for first visits, and `default_locale` last. Whatever the order, it ends in one validated value passed to `with_locale`. Interviewers asking this want the callback type, the validation and the reason `with_locale` beats assignment.
- Why does an error page rendered by rescue_from come out in the default locale?In `ActionController::Base`, `Rescue` wraps the callbacks, so an exception first unwinds the `around_action`; `with_locale`'s `ensure` restores the previous locale, and only then does the `rescue_from` handler render. Re-apply the locale inside the handler, for example by calling `I18n.with_locale(resolved_locale) { render ... }`.
- What does I18n.with_locale(params[:locale], &action) do when the request has no locale param?`with_locale(nil)` just yields without touching the locale, so the action runs in whatever the thread currently holds, normally the default. Resolving an explicit default first, as the concern does, makes the result independent of what an earlier request left behind.
- How do you build a language switcher that links to the same page in each locale?Pass the locale explicitly, for example `url_for(locale: :de)` or `tour_path(@tour, locale: :de)`, instead of changing `I18n.locale` in a loop, because `default_url_options` is evaluated once per request and its result is cached.
- A before_action that assigns I18n.locale is just as safe as with_locale.
- Passing params[:locale] straight to I18n.with_locale is fine because unknown locales fall back.
- Rails sets I18n.locale from params[:locale] automatically when the route has a :locale segment.
- I18n.with_locale(nil) resets the locale to default_locale.
- rescue_from handlers always render in the locale the action used.