Rails Model Translations

As described in the Rails Guides for translating 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.

This becomes very handy when you use form_for in Rails. You do not even have to write Model.human_attribute_name(attribute) because its content will be loaded automatically. Example:

Your active record model i18n file might look like this:

        one: Webinar presenter
        other: Webinar presenters
        webinar_id: Webinar
        presenter_email: Presenter email

Then this will automatically load the depending attribute names for the set locale:

<%= form_for @webinar_presenter do |f| %>
  <%= f.label :presenter_email %>
  <%= f.text_field :presenter_email %>
<% end %>

Because we had to translate some projects I wrote the I18n Model Translator Gem a little gem that has some rake tasks available to generate those i18n model files automatically for the english language, given that you have used descriptive column names for you models. Feedback is very welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *