More at More Ruby on Rails

Rails Internationalization (I18n) API


The process of "internationalization" usually means to abstract all strings and other locale specific bits (such as date or currency formats) out of your application. The process of "localization" means to provide translations and localized formats for these bits.1


In the process of localizing your application you'll probably want to do the following three things:

This guide will walk you through the I18n API and contains a tutorial on how to internationalize a Rails application from the start.

After reading this guide, you will know:


1 How I18n in Ruby on Rails Works


  • providing support for English and similar languages out of the box
  • making it easy to customize and extend everything for other languages

As part of this solution, every static string in the Rails framework - e.g. Active Record validation messages, time and date formats - has been internationalized, so localization of a Rails application means "over-riding" these defaults.

1.1 The Overall Architecture of the Library

Thus, the Ruby I18n gem is split into two parts:

  • The public API of the i18n framework - a Ruby module with public methods that define how the library works



1.2 The Public I18n API

The most important methods of the I18n API are:

translate # Lookup text translations
localize  # Localize Date and Time objects to local formats


I18n.t 'store.title'

There are also attribute readers and writers for the following attributes:

load_path         # Announce your custom translation files
locale            # Get and set the current locale
default_locale    # Get and set the default locale
exception_handler # Use a different exception_handler
backend           # Use a different backend

So, let's internationalize a simple Rails application from the ground up in the next chapters!

2 Setup the Rails Application for Internationalization


2.1 Configure the I18n Module




  hello: "Hello world"

This means, that in the :en locale, the key hello will map to the Hello world string. Every string inside Rails is internationalized in this way, see for instance Active Model validation messages in the activemodel/lib/active_model/locale/en.yml file or time and date formats in the activesupport/lib/active_support/locale/en.yml file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend.

The I18n library will use English as a default locale, i.e. if you don't set a different locale, :en will be used for looking up translations.

The i18n library takes a pragmatic approach to locale keys (after some discussion), including only the locale ("language") part, like :en, :pl, not the region part, like :en-US or :en-GB, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as :cs, :th or :es (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the :en-US locale you would have $ as a currency symbol, while in :en-GB, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a :en-GB dictionary. Various Rails I18n plugins such as Globalize3 may help you implement it.



The default application.rb files has instructions on how to add locales from another directory and how to set a different default locale. Just uncomment and edit the specific lines.

# config.i18n.default_locale = :de

2.2 Optional: Custom I18n Configuration Setup

For the sake of completeness, let's mention that if you do not want to use the application.rb file for some reason, you can always wire up things manually, too.

To tell the I18n library where it can find your custom translation files you can specify the load path anywhere in your application - just make sure it gets run before any translations are actually looked up. You might also want to change the default locale. The simplest thing possible is to put the following into an initializer:

# in config/initializers/locale.rb

# tell the I18n library where to find your translations
I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]

# set default locale to something other than :en
I18n.default_locale = :pt

2.3 Setting and Passing the Locale

If you want to translate your Rails application to a single language other than English (the default locale), you can set I18n.default_locale to your locale in application.rb or an initializer as shown above, and it will persist through the requests.


You may be tempted to store the chosen locale in a session or a cookie, however do not do this. The locale should be transparent and a part of the URL. This way you won't break people's basic assumptions about the web itself: if you send a URL to a friend, they should see the same page and content as you. A fancy word for this would be that you're being RESTful. Read more about the RESTful approach in Stefan Tilkov's articles. Sometimes there are exceptions to this rule and those are discussed below.

The setting part is easy. You can set the locale in a before_action in the ApplicationController like this:

before_action :set_locale

def set_locale
  I18n.locale = params[:locale] || I18n.default_locale

This requires you to pass the locale as a URL query parameter as in (This is, for example, Google's approach.) So http://localhost:3000?locale=pt will load the Portuguese localization, whereas http://localhost:3000?locale=de would load the German localization, and so on. You may skip the next section and head over to the Internationalize your application section, if you want to try things out by manually placing the locale in the URL and reloading the page.

Of course, you probably don't want to manually include the locale in every URL all over your application, or want the URLs look differently, e.g. the usual versus Let's discuss the different options you have.

2.4 Setting the Locale from the Domain Name


  • The locale is an obvious part of the URL.
  • People intuitively grasp in which language the content will be displayed.
  • It is very trivial to implement in Rails.

You can implement it like this in your ApplicationController:

before_action :set_locale

def set_locale
  I18n.locale = extract_locale_from_tld || I18n.default_locale

# You have to put something like:
def extract_locale_from_tld
  parsed_locale ='.').last ? parsed_locale : nil


# You have to put something like:
# gr.application.local
def extract_locale_from_subdomain
  parsed_locale = request.subdomains.first ? parsed_locale : nil




This solution has aforementioned advantages, however, you may not be able or may not want to provide different localizations ("language versions") on different domains. The most obvious solution would be to include locale code in the URL params (or request path).

2.5 Setting the Locale from the URL Params

The most usual way of setting (and passing) the locale would be to include it in URL params, as we did in the I18n.locale = params[:locale] before_action in the first example. We would like to have URLs like or in this case.

This approach has almost the same set of advantages as setting the locale from the domain name: namely that it's RESTful and in accord with the rest of the World Wide Web. It does require a little bit more work to implement, though.

Getting the locale from params and setting it accordingly is not hard; including it in every URL and thus passing it through the requests is. To include an explicit option in every URL (e.g. link_to( books_url(locale: I18n.locale))) would be tedious and probably impossible, of course.

Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its ApplicationController#default_url_options, which is useful precisely in this scenario: it enables us to set "defaults" for url_for and helper methods dependent on it (by implementing/overriding this method).

We can include something like this in our ApplicationController then:

# app/controllers/application_controller.rb
def default_url_options(options={})
  { locale: I18n.locale }


You may be satisfied with this. It does impact the readability of URLs, though, when the locale "hangs" at the end of every URL in your application. Moreover, from the architectural standpoint, locale is usually hierarchically above the other parts of the application domain: and URLs should reflect this.

You probably want URLs to look like this: (which loads the English locale) and (which loads the Dutch locale). This is achievable with the "over-riding default_url_options" strategy from above: you just have to set up your routes with scoping option in this way:

# config/routes.rb
scope "/:locale" do
  resources :books

Now, when you call the books_path method you should get "/en/books" (for the default locale). An URL like http://localhost:3001/nl/books should load the Dutch locale, then, and following calls to books_path should return "/nl/books" (because the locale changed).

If you don't want to force the use of a locale in your routes you can use an optional path scope (denoted by the parentheses) like so:

# config/routes.rb
scope "(:locale)", locale: /en|nl/ do
  resources :books

With this approach you will not get a Routing Error when accessing your resources such as http://localhost:3001/books without a locale. This is useful for when you want to use the default locale when one is not specified.

Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. An URL like http://localhost:3001/nl will not work automatically, because the root to: "books#index" declaration in your routes.rb doesn't take locale into account. (And rightly so: there's only one "root" URL.)

You would probably need to map URLs like these:

# config/routes.rb
get '/:locale' => 'dashboard#index'

Do take special care about the order of your routes, so this route declaration does not "eat" other ones. (You may want to add it directly before the root :to declaration.)

Have a look at two plugins which simplify work with routes in this way: Sven Fuchs's routing_filter and Raul Murciano's translate_routes.

2.6 Setting the Locale from the Client Supplied Information

In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users' preferred language (set in their browser), can be based on the users' geographical location inferred from their IP, or users can provide it simply by choosing the locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites - see the box about sessions, cookies and RESTful architecture above.

2.6.1 Using Accept-Language



def set_locale
  I18n.locale = extract_locale_from_accept_language_header

  def extract_locale_from_accept_language_header

Of course, in a production environment you would need much more robust code, and could use a plugin such as Iain Hecker's http_accept_language or even Rack middleware such as Ryan Tomayko's locale.

2.6.2 Using GeoIP (or Similar) Database

Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as GeoIP Lite Country. The mechanics of the code would be very similar to the code above - you would need to query the database for the user's IP, and look up your preferred locale for the country/region/city returned.

2.6.3 User Profile

You can also provide users of your application with means to set (and possibly over-ride) the locale in your application interface, as well. Again, mechanics for this approach would be very similar to the code above - you'd probably let users choose a locale from a dropdown list and save it to their profile in the database. Then you'd set the locale to this value.

3 Internationalizing your Application

OK! Now you've initialized I18n support for your Ruby on Rails application and told it which locale to use and how to preserve it between requests. With that in place, you're now ready for the really interesting stuff.

Let's internationalize our application, i.e. abstract every locale-specific parts, and then localize it, i.e. provide necessary translations for these abstracts.


# config/routes.rb
Rails.application.routes.draw do
  root to: "home#index"

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :set_locale

  def set_locale
    I18n.locale = params[:locale] || I18n.default_locale

# app/controllers/home_controller.rb
class HomeController < ApplicationController
  def index
    flash[:notice] = "Hello Flash"

# app/views/home/index.html.erb
<h1>Hello World</h1>

rails i18n demo untranslated

3.1 Adding Translations

Obviously there are two strings that are localized to English. In order to internationalize this code, replace these strings with calls to Rails' #t helper with a key that makes sense for the translation:

# app/controllers/home_controller.rb
class HomeController < ApplicationController
  def index
    flash[:notice] = t(:hello_flash)

# app/views/home/index.html.erb


rails i18n demo translation missing


So let's add the missing translations into the dictionary files (i.e. do the "localization" part):

# config/locales/en.yml
  hello_world: Hello world!
  hello_flash: Hello flash!

# config/locales/pirate.yml
  hello_world: Ahoy World
  hello_flash: Ahoy Flash

There you go. Because you haven't changed the default_locale, I18n will use English. Your application now shows:

rails i18n demo translated to English


rails i18n demo translated to pirate


You may use YAML (.yml) or plain Ruby (.rb) files for storing your translations in SimpleStore. YAML is the preferred option among Rails developers. However, it has one big disadvantage. YAML is very sensitive to whitespace and special characters, so the application may not load your dictionary properly. Ruby files will crash your application on first request, so you may easily find what's wrong. (If you encounter any "weird issues" with YAML dictionaries, try putting the relevant portion of your dictionary into a Ruby file.)

3.2 Passing variables to translations

You can use variables in the translation messages and pass their values from the view.

# app/views/home/index.html.erb
<%=t 'greet_username', user: "Bill", message: "Goodbye" %>

# config/locales/en.yml
  greet_username: "%{message}, %{user}!"

3.3 Adding Date/Time Formats

OK! Now let's add a timestamp to the view, so we can demo the date/time localization feature as well. To localize the time format you pass the Time object to I18n.l or (preferably) use Rails' #l helper. You can pick a format by passing the :format option - by default the :default format is used.

# app/views/home/index.html.erb
<p><%= l, format: :short %></p>

And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English):

# config/locales/pirate.yml
      short: "arrrround %H'ish"

So that would give you:

rails i18n demo localized time to pirate

Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by translating Rails' defaults for your locale. See the rails-i18n repository at GitHub for an archive of various locale files. When you put such file(s) in config/locales/ directory, they will automatically be ready for use.

3.4 Inflection Rules For Other Locales

Rails allows you to define inflection rules (such as rules for singularization and pluralization) for locales other than English. In config/initializers/inflections.rb, you can define these rules for multiple locales. The initializer contains a default example for specifying additional rules for English; follow that format for other locales as you see fit.

3.5 Localized Views



3.6 Organization of Locale Files


For example, your config/locales directory could look like this:


This way, you can separate model and model attribute names from text inside views, and all of this from the "defaults" (e.g. date and time formats). Other stores for the i18n library could provide different means of such separation.


  # config/application.rb


4 Overview of the I18n API Features

You should have good understanding of using the i18n library now, knowing all necessary aspects of internationalizing a basic Rails application. In the following chapters, we'll cover it's features in more depth.

These chapters will show examples using both the I18n.translate method as well as the translate view helper method (noting the additional feature provide by the view helper method).

Covered are features like these:

  • looking up translations
  • interpolating data into translations
  • pluralizing translations
  • using safe HTML translations (view helper method only)
  • localizing dates, numbers, currency, etc.

4.1 Looking up Translations

4.1.1 Basic Lookup, Scopes and Nested Keys


I18n.t :message
I18n.t 'message'

The translate method also takes a :scope option which can contain one or more additional keys that will be used to specify a "namespace" or scope for a translation key:

I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]

This looks up the :record_invalid message in the Active Record error messages.


I18n.translate "activerecord.errors.messages.record_invalid"

Thus the following calls are equivalent:

I18n.t 'activerecord.errors.messages.record_invalid'
I18n.t 'errors.messages.record_invalid', scope: :active_record
I18n.t :record_invalid, scope: 'activerecord.errors.messages'

4.1.2 Defaults


I18n.t :missing, default: 'Not here'
# => 'Not here'


E.g., the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result, the string "Not here" will be returned:

I18n.t :missing, default: [:also_missing, 'Not here']
# => 'Not here'

4.1.3 Bulk and Namespace Lookup


I18n.t [:odd, :even], scope: 'errors.messages'


I18n.t 'activerecord.errors.messages'

4.1.4 "Lazy" Lookup


      title: "Título"


<%= t '.title' %>

Automatic translation scoping by partial is only available from the translate view helper method.

4.2 Interpolation



I18n.backend.store_translations :en, thanks: 'Thanks %{name}!'
I18n.translate :thanks, name: 'Jeremy'
# => 'Thanks Jeremy!'


4.3 Pluralization

In English there are only one singular and one plural form for a given string, e.g. "1 message" and "2 messages". Other languages (Arabic, Japanese, Russian and many more) have different grammars that have additional or fewer plural forms. Thus, the I18n API provides a flexible pluralization feature.


I18n.backend.store_translations :en, inbox: {
  one: 'one message',
  other: '%{count} messages'
I18n.translate :inbox, count: 2
# => '2 messages'

I18n.translate :inbox, count: 1
# => 'one message'

The algorithm for pluralizations in :en is as simple as:

entry[count == 1 ? 0 : 1]



4.4 Setting and Passing a Locale


If no locale is passed, I18n.locale is used:

I18n.locale = :de
I18n.t :foo

Explicitly passing a locale:

I18n.t :foo, locale: :de
I18n.l, locale: :de


I18n.default_locale = :de

4.5 Using Safe HTML Translations

Keys with a '_html' suffix and keys named 'html' are marked as HTML safe. When you use them in views the HTML will not be escaped.

# config/locales/en.yml
  welcome: <b>welcome!</b>
  hello_html: <b>hello!</b>
    html: <b>title!</b>

# app/views/home/index.html.erb
<div><%= t('welcome') %></div>
<div><%= raw t('welcome') %></div>
<div><%= t('hello_html') %></div>
<div><%= t('title.html') %></div>

Automatic conversion to HTML safe translate text is only available from the translate view helper method.

i18n demo html safe

5 How to Store your Custom Translations


For example a Ruby Hash providing translations can look like this:

  pt: {
    foo: {
      bar: "baz"

The equivalent YAML file would look like this:

    bar: baz

As you see, in both cases the top level key is the locale. :foo is a namespace key and :bar is the key for the translation "baz".

Here is a "real" example from the Active Support en.yml translations YAML file:

      default: "%Y-%m-%d"
      short: "%b %d"
      long: "%B %d, %Y"

So, all of the following equivalent lookups will return the :short date format "%b %d":

I18n.t 'date.formats.short'
I18n.t 'formats.short', scope: :date
I18n.t :short, scope: 'date.formats'
I18n.t :short, scope: [:date, :formats]


5.1 Translations for Active Record Models

You can use the methods Model.model_name.human and Model.human_attribute_name(attribute) to transparently look up translations for your model and attribute names.

For example when you add the following translations:

      user: Dude
        login: "Handle"
      # will translate User attribute "login" as "Handle"

Then User.model_name.human will return "Dude" and User.human_attribute_name("login") will return "Handle".

You can also set a plural form for model names, adding as following:

        one: Dude
        other: Dudes

Then User.model_name.human(count: 2) will return "Dudes". With count: 1 or without params will return "Dude".

5.1.1 Error Message Scopes


This gives you quite powerful means to flexibly adjust your messages to your application's needs.

Consider a User model with a validation for the name attribute like this:

class User < ActiveRecord::Base
  validates :name, presence: true






class Admin < User
  validates :name, presence: true

Then Active Record will look for messages in this order:


5.1.2 Error Message Interpolation


So, for example, instead of the default error message "cannot be blank" you could use the attribute name like this : "Please fill in your %{attribute}".

validation with option message interpolation
confirmation - :confirmation -
acceptance - :accepted -
presence - :blank -
absence - :present -
length :within, :in :too_short count
length :within, :in :too_long count
length :is :wrong_length count
length :minimum :too_short count
length :maximum :too_long count
uniqueness - :taken -
format - :invalid -
inclusion - :inclusion -
exclusion - :exclusion -
associated - :invalid -
numericality - :not_a_number -
numericality :greater_than :greater_than count
numericality :greater_than_or_equal_to :greater_than_or_equal_to count
numericality :equal_to :equal_to count
numericality :less_than :less_than count
numericality :less_than_or_equal_to :less_than_or_equal_to count
numericality :only_integer :not_an_integer -
numericality :odd :odd -
numericality :even :even -
5.1.3 Translations for the Active Record error_messages_for Helper


Rails ships with the following translations:

          one:   "1 error prohibited this %{model} from being saved"
          other: "%{count} errors prohibited this %{model} from being saved"
        body:    "There were problems with the following fields:"

In order to use this helper, you need to install DynamicForm gem by adding this line to your Gemfile: gem 'dynamic_form'.

5.2 Translations for Action Mailer E-Mail Subjects

If you don't pass a subject to the mail method, Action Mailer will try to find it in your translations. The performed lookup will use the pattern <mailer_scope>.<action_name>.subject to construct the key.

# user_mailer.rb
class UserMailer < ActionMailer::Base
  def welcome(user)

      subject: "Welcome to Rails Guides!"

5.3 Overview of Other Built-In Methods that Provide I18n Support

Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers. Here's a brief overview.

5.3.1 Action View Helper Methods

  • datetime_select and select_month use translated month names for populating the resulting select tag. See date.month_names for translations. datetime_select also looks up the order option from date.order (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the datetime.prompts scope if applicable.


5.3.2 Active Model Methods
  • model_name.human and human_attribute_name use translations for model names and attribute names if available in the activerecord.models scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".

  • ActiveModel::Errors#generate_message (which is used by Active Model validations but may also be used manually) uses model_name.human and human_attribute_name (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".

  • ActiveModel::Errors#full_messages prepends the attribute name to the error message using a separator that will be looked up from errors.format (and which defaults to "%{attribute} %{message}").

5.3.3 Active Support Methods

6 Customize your I18n Setup

6.1 Using Different Backends

For several reasons the Simple backend shipped with Active Support only does the "simplest thing that could possibly work" for Ruby on Rails3 ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but cannot dynamically store them to any format.

That does not mean you're stuck with these limitations, though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:

I18n.backend =

You can also use the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends. For example, you could use the Active Record backend and fall back to the (default) Simple backend:

I18n.backend =, I18n.backend)

6.2 Using Different Exception Handlers


MissingTranslationData       # no translation was found for the requested key

The I18n API will catch all of these exceptions when they are thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for MissingTranslationData exceptions. When a MissingTranslationData exception has been caught, it will return the exception's error message string containing the missing key/scope.

The reason for this is that during development you'd usually want your views to still render even though a translation is missing.

In other contexts you might want to change this behavior, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module or a class with #call method:

module I18n
  class JustRaiseExceptionHandler < ExceptionHandler
    def call(exception, locale, key, options)
      if exception.is_a?(MissingTranslation)
        raise exception.to_exception

I18n.exception_handler =

This would re-raise only the MissingTranslationData exception, passing all other input to the default exception handler.

However, if you are using I18n::Backend::Pluralization this handler will also raise I18n::MissingTranslationData: translation missing: en.i18n.plural.rule exception that should normally be ignored to fall back to the default pluralization rule for English locale. To avoid this you may use additional check for translation key:

if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule'
  raise exception.to_exception



I18n.t :foo, raise: true # always re-raises exceptions from the backend

7 Conclusion


If you find anything missing or wrong in this guide, please file a ticket on our issue tracker. If you want to discuss certain portions or have questions, please sign up to our mailing list.

8 Contributing to Rails I18n

I18n support in Ruby on Rails was introduced in the release 2.2 and is still evolving. The project follows the good Ruby on Rails development tradition of evolving solutions in plugins and real applications first, and only then cherry-picking the best-of-breed of most widely useful features for inclusion in the core.

Thus we encourage everybody to experiment with new ideas and features in plugins or other libraries and make them available to the community. (Don't forget to announce your work on our mailing list)


9 Resources

10 Authors

If you found this guide useful, please consider recommending its authors on workingwithrails.

11 Footnotes





You're encouraged to help improve the quality of this guide.



