Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

Rails Internationalization (I18n) in model validations: Possible or not?

I have the following validation in a model:

validates_inclusion_of :whatever, :in => [true, false], :message => I18n.t('please_select_whatever')

It seems that the translation does not work in production mode: in all languages it's always the english translation that gets diplayed (probably because I set english as the default locale in my app...?).

So I am assuming that we can't translate validations in models, because models get loaded only once - when the server is booted (and then, the default locale would be applied).

Am I right? If yes, how would you solve this problem?

Thanks for your help!

question from:https://stackoverflow.com/questions/4451076/rails-internationalization-i18n-in-model-validations-possible-or-not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The solution is to NOT include any custom message keys in the models, like...

:message => I18n.t('activerecord.errors.models.my_model.attributes.whatever.please_select_whatever')

The model will then apply the default message keys, for example ":inclusion" in the case of "validates_inclusion_of"

...and in config/locales/en.yml you need to have:

en:
  activerecord:
    errors:
      models:
        my_model:
          attributes:
            whatever:
              inclusion: "Please select whatever." # see default key: "inclusion"

for reference, check out the respective Rails guide:

http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...