-
Type: Bug
-
Resolution: Fixed
-
Priority: Unknown
-
Affects Version/s: None
-
Component/s: None
-
Minor Change
UniquenessValidator does not work properly with I18n; the error message is always "stuck" in English. (A non-English user of my app reported this.)
For all validation error message types EXCEPT uniqueness, adding Rails I18n gem will translate them automatically into the correct locale. Uniqueness is broken in Mongoid and will be stuck in English. (It works correctly in ActiveRecord.)
The root cause is as follows:
- When the UniquenessValidator fails, it sets an I18n message "taken"
- Both the Rails I18n gem AND ActiveRecord put the "taken" message under errors.messages.taken (NOT active_record.errors.messages.taken)
- You can see it here in ActiveRecord https://github.com/rails/rails/blob/main/activerecord/lib/active_record/locale/en.yml#L11
- And here in Rails I18n: https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en.yml#L132
- The Rails I18n gem looks for message translations first under {{{}
{i18n_scope}
.errors.messages.taken{}}}, THEN under errors.messages.taken. Note that i18n_scope for Mongoid is :mongoid (set in Mongoid::Document)
- Mongoid puts the translation for taken under mongoid.errors.messages.taken, and because the key exists there, it prevents Rails I18n from falling back correctly as AR does
- To fix this, we simply need to move the translation in the Mongoid lib to errors.messages.taken, which is what AR / Rails I18n do, as per links above.
Note that Rails I18n moved the location of the key in 2011: https://github.com/svenfuchs/rails-i18n/blob/master/CHANGELOG.md?plain=1#L579
I've raised a PR here to fix the issue: https://github.com/mongodb/mongoid/pull/5262. This PR also updates the message to use the same text as latest AR / Rails I18n.