Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I translate the ActiveRecord attribute name in Rails 3.2?

I have the following validation in my model ( User ):

  validates :first_name,:length => {:minimum => 2,:maximum => 50},:format => { :with => /[a-zA-Z]+/ }

I have the following in my yml locales file:

 attributes:
   first_name:
     too_short: "First name is too short"
     too_long: "First name is too long"
     invalid: "First name is not valid"

Now, if I start a rails console, and write the following:

a = User.new
a.valid?
a.errors.full_messages

I will see the following errors:

["First name First name is too short", "First name First name is not valid"]

As you can see, the attribute name is also prepended to the field error. So far, everywhere in my code, I have used model.errors[:field], and this will always show me the string I have in the yml file, but I'd like to change the strings to:

 attributes:
   first_name:
     too_short: " is too short"
     too_long: " is too long"
     invalid: " is not valid"

And use the full_messages version. The problem is, I don't know how to translate the attribute name. Let's say for example, that I'd like instead of First name, to have Name first. How would I do it?

like image 205
Geo Avatar asked May 30 '12 08:05

Geo


2 Answers

You can find the answer here http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

in your config/locale/(your_lang).yml

en: 
  activerecord:
    models:
      user: Dude
    attributes:
      user:
        first_name: "Name first"

change "en:" with the language symbol that you need to use

cheers

like image 115
mingle Avatar answered Nov 01 '22 01:11

mingle


In Rails 5, after attributes, I had to namespace with my model's name in underscore. Like this:

pt-BR:
  activerecord:
    attributes:
      my_model_name_in_underscore: 
        attribute_name: 'String'  

Source: https://stackoverflow.com/a/5526812/1290457

like image 29
sandre89 Avatar answered Nov 01 '22 01:11

sandre89