user2320239
user2320239

Reputation: 1038

Localization of custom validations

I'm working on a project in which I'd like to move all strings used in the app to a single file, so they can be easily changed and updated. However I'm having trouble with the custom validation. I have validations in my app as follows:

validate :thing_is_correct

def thing_is_correct
  unless thing.is_correct
    errors[:base] << "Thing must be correct"
  end
end

I'm not sure how to move "Thing must be correct" into my en.yml file and out of the model. Any help would be greatly appreciated.

Upvotes: -1

Views: 1558

Answers (2)

Greg Navis
Greg Navis

Reputation: 2934

The Rails Way to do that would be to use the mechanism described in the Guides.

errors is an instance of ActiveModel::Errors. New messages can be added by calling ActiveModel::Errors#add. As you can see in the docs, you can not only pass a message but also a symbol representing the error:

def thing_is_correct
  unless thing.is_correct?
    errors.add(:thing, :thing_incorrect)
  end
end

Active Model will automatically try fetching the message from the namespaces described in the Guides (see the link above). The actual message is generated using ActiveModel::Errors#generate_message.

To sum up:

  1. Use errors.add(:think, :thing_incorrect)
  2. Add thing_incorrect under one of the YAML keys listed in the Guides.

Upvotes: 1

Pedro Adame Vergara
Pedro Adame Vergara

Reputation: 592

You can access the I18n inside the model.

validate :thing_is_correct

def thing_is_correct
  unless thing.is_correct
    errors[:base] << I18n.t('mymodel.mymessage')
  end
end

Inside config/locales/en.yml

en:
  mymodel:
    mymessage: "Thing must be correct"

Inside another locale: (config/locales/es.yml)

es:
  mymodel:
    mymessage: "Esto debe ser correcto"

If you set I18n.locale = :en, the message inside en.yml will be displayed. If you set it to :es, the one inside es.yml will be used instead.

Upvotes: -1

Related Questions