Translating models in ruby on rails

By Rasmus

I had to translate a model in Ruby on Rails. The example (in: http://guides.rails.info/i18n.html#translations-for-active-record-models) was:

activerecord:
  models:
    user: Dude
  attributes:
    user:
      login: "Handle"

Well that didn’t work for me. My only difference was that my model name consisted of two words, so in my yml file I had the following:

activerecord:
  models:
    email_template: Email template
  attributes:
    email_template:
      name: Name
      subject: Subject
      body: Body

But this did not work in the “error_messages_for”. Well the attribute names did, but not the model name that remained untranslated.

After an hour of Googling I didn’t have any answers until I tried to ad a space instead of the “underscore” in the model name. THAT WORKED. So now my yaml file looks like the following. Notice the inconsistencies in the model name!

activerecord:
  models:
    email template: Email template
  attributes:
    email_template:
    name: Name
    subject: Subject
    body: Body

Looking at the source code for the helper method “error_messages_for” we find the thing bothering me here:

          I18n.with_options :locale => options[:locale], :scope => [:activerecord, :errors, :template] do |locale|
            header_message = if options.include?(:header_message)
              options[:header_message]
            else
              object_name = options[:object_name].to_s.gsub('_', ' ')
              object_name = I18n.t(options[:object_name].to_s, :default => object_name, :scope => [:activerecord, :models], :count => 1)
              locale.t :header, :count => count, :model => object_name
            end

(line 199 of active_record_helper.rb)

object_name = options[:object_name].to_s.gsub('_', ' ')

?!?! They are replacing the underscores instead of doing something like:

eval(resource_name.classify).human_name

Has someone else noticed this?! And what are your fixes?
Currently I have to write the model name twice in my yaml files. This is not DRY. My file ended up looking like:

  activerecord:
    models:
      # used by EmailTemplate.human_name
      email_template: "Email template"
      # used by error_messages_for (go figure?!?)
      email template: "Email template"
    attributes:
      email_template:
        name: Name
        subject: Subject
        body: Body

Tags:

Leave a Reply