Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 360
TomDogg Avatar asked Dec 15 '10 14:12

TomDogg


People also ask

What is i18n internationalization?

Internationalization (sometimes shortened to "I18N , meaning "I - eighteen letters -N") is the process of planning and implementing products and services so that they can easily be adapted to specific local languages and cultures, a process called localization .

Why is internationalization called i18n?

Internationalization (i18n) Example Internationalization is also called i18n (because of the number of letters, 18, between “i” and “n”). Internationalization ensures your software is localizable and is typically done by software developers and engineers.

What is i18n and l10n?

Internationalization (i18n) is the process of developing products in such a way that they can be localized for languages and cultures easily. Localization (l10n), is the process of adapting applications and text to enable their usability in a particular cultural or linguistic market.

What is locale i18n?

Internationalization, sometimes referenced as i18n, is the process of designing and preparing your project for use in different locales around the world. Localization is the process of building versions of your project for different locales.


1 Answers

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

like image 152
TomDogg Avatar answered Oct 24 '22 20:10

TomDogg