skip to content

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%

answer

  1. count both interpolates and selects
  2. Simple backend: English rule only
  3. zero: used only when present
  4. I18n::InvalidPluralizationData on a missing subkey
  5. Backend::Pluralization plus i18n.plural.rule

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.

solid answer

~40 s

`t("campsites.show.nights", count: n)` uses `count` twice: it is interpolated into `%{count}` and it selects a subkey of the hash stored at that key. The default `I18n::Backend::Simple` knows only the English rule: `:zero` when count is 0 and a `zero:` key exists, `:one` when count equals 1, `:other` otherwise. If the chosen subkey is missing it raises `I18n::InvalidPluralizationData`, whatever the raise-on-missing setting. French puts 0 in its singular category, so the Simple backend renders "0 nuits" where "0 nuit" is correct. The fix is to include `I18n::Backend::Pluralization` into the Simple backend and store a rule lambda at `fr.i18n.plural.rule`, from a Ruby locale file because YAML cannot hold a lambda. With that module, a category missing from the entry falls back to `other:`.

code

yaml · 6 lines
yaml
fr:
  campsites:
    show:
      nights:
        one: "%{count} nuit"
        other: "%{count} nuits"

go deeper

for a junior

Recall that count: selects one or other and fills %{count}, and that the entry must be a hash with those keys.

for a middle

Explain the Simple backend's English-only rule, when zero: applies, and why a missing subkey raises InvalidPluralizationData.

for a senior

Show how you enable locale rules with the Pluralization module, test categories per locale, and keep counts numeric when they come from params.

for a principal

Weigh hand-maintained plural rules against a community locale-data gem for each launched language, and how translators learn which categories each locale needs.

## What `count:` does In Rails I18n the **`count`** option is special. Every other option you pass to `t` is only an interpolation value, but `count` does two jobs: 1. It **selects a subkey** when the translation stored at the key is a hash of plural forms. 2. It is **interpolated** wherever the string contains `%{count}`. ```yaml fr: campsites: show: nights: one: "%{count} nuit" other: "%{count} nuits" ``` `t(".nights", count: 3)` in `campsites/show.html.erb` returns `"3 nuits"`. If the value at the key is a plain string rather than a hash, `count` is simply interpolated and no selection happens. ## The Simple backend's rule The default backend, `I18n::Backend::Simple`, ships one rule for every locale, the English one: | `count` | Subkey chosen | |---|---| | `0` and a `zero:` key exists | `zero` | | `1` | `one` | | anything else (including `0` without `zero:`) | `other` | If the chosen subkey is absent, the backend **raises `I18n::InvalidPluralizationData`**. That is a raise, not the soft "translation missing" path, so it reaches the error page even when `raise_on_missing_translations` is off. A common way to hit it is an entry with only `other:` and a count of 1. The comparison is `count == 1`, so a count that arrives as the string `"1"` (straight from `params`) selects `other`. Convert to an integer first. ## Why French needs more Plural categories come from the Unicode CLDR rules, and they differ by language. English has two categories (`one`, `other`). French also has `one` and `other`, but its `one` covers **0 and 1**, so "0 nuit" is singular. Polish, Russian or Arabic need `few`, `many` or `two`, which the Simple backend never chooses. | count | English via Simple | French correct form | French via Simple | |---|---|---|---| | 0 | other | one ("0 nuit") | other ("0 nuits") | | 1 | one | one | one | | 2 | other | other | other | ## Turning on locale-specific rules The i18n gem ships **`I18n::Backend::Pluralization`**. Once it is included in the Simple backend, each lookup with `count` reads a callable from `i18n.plural.rule` in the current locale and uses the category it returns. ```ruby # config/initializers/i18n.rb I18n::Backend::Simple.include(I18n::Backend::Pluralization) # config/locales/plurals.rb (a .rb locale file returns a Hash) { fr: { i18n: { plural: { rule: ->(n) { n >= 0 && n < 2 ? :one : :other } } } } } ``` Points worth knowing about the module: - The rule must live in a **Ruby locale file** (or `store_translations`), because YAML cannot express a lambda. Files under `config/locales` ending in `.rb` are loaded like YAML ones. - When the rule's category is missing from the entry, the module **falls back to `other:`** instead of raising. - It honours explicit `"0"` and `"1"` keys for wording such as "aucune nuit", and keeps the old `zero:` behaviour only for compatibility. - Store a rule for **every locale you serve**: a locale without one gets the English behaviour, and with raise-on-missing enabled the rule lookup itself raises. Community locale-data gems bundle such rules for many languages, so you rarely write them by hand for every locale. ## Formatting the number itself `count` is interpolated as the raw number, so `count: 1500` prints "1500 nuits" even where French readers expect "1 500". Keep `count` numeric for category selection and pass a second, formatted value for display: ```erb <%= t(".nights", count: @stay.nights, formatted: number_with_delimiter(@stay.nights)) %> ``` with `other: "%{formatted} nuits"` in the YAML. A quick test per locale (`I18n.with_locale(:fr) { I18n.t("campsites.show.nights", count: 0) }`) pins the category choice down before a translator edits the file. ## Pitfalls interviewers probe - **The `pluralize` view helper is a different tool.** `pluralize(3, "nuit")` uses `ActiveSupport::Inflector` word rules, which are English unless you register inflections for the locale, and it cannot reorder a phrase. Use `t` with `count:` for sentences. - **Every locale needs every category its rule returns.** A Polish entry without `few:` silently falls back to `other:` under the Pluralization module, and on the plain Simple backend `few` is never chosen at all; either way the grammar is wrong with no error, so review plural entries per locale. - **Do not concatenate** `"#{n} " + t("night")`; let the translation own the number's position. - **Model names** pluralize the same way: `Campsite.model_name.human(count: 2)` selects `other:` under `activerecord.models.campsite`. An interviewer asking this wants the double role of `count`, the English-only default and a concrete fix, not a list of CLDR categories.

  • With the Simple backend, what happens when count is 1 and the entry has only an other: key?
    The backend picks `:one`, finds no such subkey and raises `I18n::InvalidPluralizationData`. That error is raised directly, not routed through the missing-translation handler, so it surfaces even with raise-on-missing off. Adding `one:` fixes it; with `I18n::Backend::Pluralization` included, a missing category falls back to `other:` instead.
  • Why can't the French plural rule go into fr.yml?
    The rule is a callable that receives the count and returns a category symbol, and YAML has no way to express a lambda. Rails also loads `.rb` files from `config/locales`; such a file evaluates to a Hash, so `{ fr: { i18n: { plural: { rule: ->(n) { ... } } } } }` works.
  • How would you show 'aucune nuit' for zero without breaking the French singular rule?
    With `I18n::Backend::Pluralization` loaded, add an explicit `"0"` key to the entry; the module checks the explicit `0` and `1` keys before applying the rule. On the plain Simple backend a `zero:` key does the same job, since it is chosen whenever count is 0 and the key exists.

  • The Simple backend applies each locale's CLDR plural rules automatically.
  • A missing one: subkey just renders a translation_missing span like any missing key.
  • pluralize(count, 'nuit') is the right helper for translated plural sentences.
  • The zero: key is required, otherwise count 0 raises an error.
  • A French plural rule lambda can be written directly in fr.yml.