skip to content

I18n Translations

Rails apps are translated with the I18n API: YAML locale files, t and l lookups, and a locale chosen per request. Interviewers probe missing keys, plural forms and locales leaking across requests.

part ofRuby on Railsread it →
on this pageshow

explore

questions

12

In a Rails view, what does t('.title') look up, and where do the translations it reads come from?

level: juniorimportance: must knowfreq 68%

answer

  1. relative key, the template decides
  2. slashes and partial underscore become dots
  3. config/locales/**/*.{rb,yml}, loaded automatically
  4. controller: path.action.key, then path.key
  5. span class translation_missing

basics

~10 s

A leading dot makes the view helper t scope the key by the current template: t('.title') in app/views/campsites/index.html.erb reads campsites.index.title from YAML or Ruby files loaded automatically from config/locales by the Simple backend.

solid answer

~40 s

Rails adds every `.yml` and `.rb` file under `config/locales` (at any depth) to `I18n.load_path`, and the default `I18n::Backend::Simple` deep-merges them into an in-memory hash keyed by the top-level locale key (`fr:`), not by the file name. In a view, `t` (alias of `translate`) treats a key starting with a dot as relative: it takes the template's virtual path, turns slashes and a partial's leading underscore into dots, and prepends it. So `t(".title")` in `campsites/index.html.erb` reads `campsites.index.title`, and in `campsites/_review.html.erb` it reads `campsites.review.title`. In a controller, `t(".created")` inside `CampsitesController#create` reads `campsites.create.created`, then `campsites.created`. By default a missing key does not raise: the helper renders a `translation_missing` span with the titleized last segment.

code

yaml · 9 lines
yaml
# config/locales/views/campsites.fr.yml
fr:
  campsites:
    index:
      title: "Campings"
    review:
      posted_by: "Avis de %{name}"
    create:
      created: "Camping ajouté."

go deeper

for a junior

Recall that a leading dot means the key is relative to the template file, and that config/locales files load automatically by their top-level locale key.

for a middle

Explain how the virtual path becomes the scope, why partials drop the underscore, and how controller lazy lookup adds an action-less fallback key.

for a senior

Show how you keep keys stable through template moves, catch missing keys in CI with raise-on-missing, and decide between lazy and shared absolute keys.

for a principal

Weigh lazy per-template keys against a shared key vocabulary for translator workflow, reuse and churn when views are refactored often.

## Where Rails finds translations Rails internationalization (**I18n**) is built on the `i18n` gem. At boot, the application and every engine add their `config/locales` directory to the load path with the glob `**/*.{rb,yml}`, so `config/locales/fr.yml`, `config/locales/views/campsites.fr.yml` and `config/locales/models/fr.yml` are all picked up without extra configuration. The **file name does not decide the locale**: the top-level key inside the file does (`fr:`). File names are a team convention only. The default backend is **`I18n::Backend::Simple`**. It reads each file, deep-merges the data into an in-memory hash keyed by locale, and answers every lookup from that hash. Because the merge is deep, two files can both contribute keys under `fr.campsites`; a later file overwrites an earlier one only at the deepest level. In development, Rails watches those directories and reloads changed or added locale files without a restart. A short French file for a campsite-review app: ```yaml fr: campsites: index: title: "Campings" review: posted_by: "Avis de %{name}" ``` ## How a leading dot becomes a full key `t` is the view alias of `ActionView::Helpers::TranslationHelper#translate`. When the key starts with `.`, the helper takes the template's **virtual path**, replaces each `/` (and a partial's leading `_`) with `.`, and prepends the result: | Template | Call | Key looked up | |---|---|---| | `app/views/campsites/index.html.erb` | `t(".title")` | `campsites.index.title` | | `app/views/campsites/_review.html.erb` | `t(".posted_by", name: review.author_name)` | `campsites.review.posted_by` | | `app/views/admin/campsites/show.html.erb` | `t(".heading")` | `admin.campsites.show.heading` | Two consequences matter in practice: - The key follows the **file the call is written in**, not the action that rendered it. A partial rendered from three pages reads one set of keys under its own name. - Moving or renaming a template silently changes its keys, so a rename needs a matching YAML edit. If the helper has no template path to work from, it raises a `RuntimeError` saying the shortcut cannot be used, rather than guessing a scope. ## Lazy lookup outside views Controllers and mailers include **`AbstractController::Translation`**, which has its own relative-key rule built from `controller_path` and `action_name`: 1. `t(".created")` inside `CampsitesController#create` first looks up `campsites.create.created`. 2. If that is missing it tries `campsites.created`, so several actions can share one flash message. 3. Any `default:` you pass is tried after those two keys. The plain **`I18n.t`** method has no lazy behaviour at all. `I18n.t(".title")` simply drops the empty segment and reads a top-level `title` key, which is usually missing, so lazy keys belong only in views, controllers and mailers. ## What a missing key looks like In a new app, `config.i18n.raise_on_missing_translations` is commented out in the generated `development.rb` and `test.rb`, so the view helper does not raise. It renders: ```html <span class="translation_missing" title="translation missing: fr.campsites.index.title">Title</span> ``` The visible text is the titleized last key segment, so a page with gaps still reads, and the `title` attribute names the exact key to add. `I18n.t` called directly returns the plain string `"Translation missing: fr.campsites.index.title"` instead. Turning on raise-on-missing in development and test is the usual way to catch gaps before they reach users. ## Other ways to address a key Lazy keys are one of several addressing forms the helper accepts: - **Absolute keys**: `t("campsites.index.title")` works from any template and is the right choice for text shared across pages. - **`scope:`**: `t(:title, scope: [:campsites, :index])` builds the same key from parts, which reads well in helpers that loop over several keys. - **Arrays**: `t([".title", ".subtitle"])` returns an Array of translations, each resolved with the same rules. - **Block form**: `t(".title") { |text, key| ... }` yields the translation and the fully resolved key, handy for wrapping text in markup that records which key produced it. Whichever form you use, the lookup ends at the same in-memory hash, so the YAML layout is the contract between templates and translators. ## Habits that keep locale files maintainable - **Mirror the view tree** in the YAML, so a key's location is obvious from the template path. - **Split by area and locale** (`campsites.fr.yml`, `campsites.en.yml`) so translators can compare locales side by side. - **Quote YAML words** such as `"yes"`, `"no"`, `"on"` and `"off"`; YAML reads them as booleans, a warning the generated `en.yml` itself carries. - **Prefer lazy keys for page copy** and absolute keys (`t("shared.save")`) for text reused across templates. - **Pass values, not fragments**: interpolate with `%{name}` rather than concatenating translated pieces, because word order differs between languages. Lazy lookup is the opening question because it tests whether a candidate understands that the scope is derived mechanically from file paths; everything else in Rails I18n builds on that key layout.

  • Why does t('.title') inside a shared partial not pick up the key of the page that rendered it?
    Lazy lookup scopes by the virtual path of the template the call is written in. In `campsites/_review.html.erb` the prefix is always `campsites.review`, whichever page rendered the partial. If a partial needs page-specific wording, pass the text in as a local or use an absolute key; the caller's scope never leaks in.
  • What does t('.created') read inside Admin::CampsitesController#create?
    `AbstractController::Translation` builds the prefix from `controller_path` with slashes turned into dots, so it looks up `admin.campsites.create.created` first and `admin.campsites.created` second; a `default:` is tried after both. The bare `I18n.t` method does none of this scoping.
  • Does the YAML file name decide which locale its keys belong to?
    No. The Simple backend treats the top-level key inside each file (`fr:`) as the locale; the file name is a convention. A file called `campsites.fr.yml` that starts with `en:` loads English keys, which is why teams pair a naming habit with review or a key-checking tool.

  • t('.title') is scoped by the controller action that rendered the template.
  • I18n.t('.title') in a model or service scopes the key the same way the view helper does.
  • Only top-level config/locales/*.yml files load; subfolders always need load_path edits.
  • The file name fr.yml is what makes its keys French.
  • A missing key in a view raises an exception in every environment by default.
open as a page

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?

level: middleimportance: must knowfreq 62%

basics

~10 s

Add 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.

open as a page

With Rails I18n, how does t('campsites.show.nights', count: n) pick between one and other keys, and what goes wrong for French?

level: middleimportance: must knowfreq 55%

basics

~20 s

Passing count: makes I18n pick a subkey and interpolate %{count}. The default Simple backend applies only the English rule (1 is one, everything else other, zero if present), so French singular zero needs the Pluralization module and a fr plural rule.

open as a page

In a Rails app, what do config.i18n.default_locale and config.i18n.available_locales control, and what happens when code asks for an unlisted locale?

level: juniorimportance: should knowfreq 45%

basics

~20 s

default_locale (:en unless configured) is what I18n.locale returns until something sets it; available_locales is the allow list, derived from loaded translation data when unset. Since enforce_available_locales defaults to true, using an unlisted locale raises I18n::InvalidLocale.

open as a page

In a Rails app, which locale keys translate an Active Record model's name and its attribute names, and which helpers read them?

level: juniorimportance: should knowfreq 42%

basics

~10 s

Model names live under activerecord.models.campsite (one/other) and attribute names under activerecord.attributes.campsite.nightly_price. Campsite.model_name.human, Campsite.human_attribute_name, form labels, submit buttons and error full messages read them, falling back to humanized names.

open as a page

In a Rails controller, how would you take the locale from a subdomain like fr.visit-lyon.com or from the Accept-Language header, and what goes wrong?

level: middleimportance: should knowfreq 35%

basics

~10 s

Rails parses neither for you: read request.subdomains.first or request.headers['Accept-Language'], map the value onto I18n.available_locales, and fall back to default_locale. Raw values raise I18n::InvalidLocale, and naive header parsing ignores q-values and region tags.

open as a page

In a Rails view, how does l(stay.check_in_on, format: :long) produce French output, and why prefer it over strftime or to_fs?

level: middleimportance: should knowfreq 45%

basics

~20 s

l delegates to I18n.localize: a Date reads date.formats.long and a Time reads time.formats.long from the current locale, and %B, %b, %A and %a are filled from that locale's month and day names. strftime and to_fs ignore I18n and print English.

open as a page

In Rails 8.1, what happens when a t() key is missing, and how do default: and config.i18n.raise_on_missing_translations change it?

level: middleimportance: should knowfreq 48%

basics

~20 s

A missing key is soft by default: the view t renders a translation_missing span and I18n.t returns 'Translation missing: …'. default: tries other keys or literal text; raise_on_missing_translations = true raises I18n::MissingTranslationData, since Rails 7.1 for any I18n.t.

open as a page

In Rails 8.1, what does config.i18n.fallbacks = true in the generated production.rb do, and why can a missing French key look fine in production but not in development?

level: seniorimportance: should knowfreq 38%

basics

~20 s

It includes I18n::Backend::Fallbacks and builds I18n.fallbacks from default_locale, so a key missing in :fr is tried in its parent locales and then :en. Only production.rb sets it, so development shows the missing-key marker while production quietly prints English.

open as a page

When a Rails controller calls perform_later inside I18n.with_locale(:fr), which locale does the Active Job run in, and why?

level: seniorimportance: should knowfreq 32%

basics

~10 s

French. Active Job writes I18n.locale into the job's serialized 'locale' field at enqueue time, and perform_now runs perform inside I18n.with_locale(locale), so the worker translates in fr whatever its own thread's locale is.

open as a page

A Rails city-guide app assigns I18n.locale = params[:locale] in EventsController's before_action; why do visitors to other pages sometimes see German?

level: seniorimportance: should knowfreq 45%

basics

~20 s

I18n.locale is per-thread state and Puma reuses threads across requests. Rails never resets it, so German set during an events request stays on that thread and shows up on the next request whose controller sets no locale.

open as a page

In a Rails view, what does an _html suffix on a translation key change, and is t('reviews.thanks_html', name: @review.author_name) safe with user input?

level: seniorimportance: should knowfreq 30%

basics

~20 s

An _html suffix (or a final html segment) makes the t helper return an html_safe string, so markup written in the locale file renders. Interpolated values are HTML-escaped first, so passing user input stays safe.

open as a page