- I have a model with custom validations. I return the validation errors to the view as JSON using AJAX.
- I need to show the error messages with the right locale but the messages show in English (default) for each locale.
- When I return I18n.locale itself instead of the message (for troubleshooting) it shows "en" no matter what is the set locale.
- I18n in controllers or views works as expected, this problem occurs only in the model.
- The only configuration that I've made regarding locale is setting the default locale in the application config and setting the locale before each action in the application controller.
- Another thing that I've noticed is that when I use root_path without providing the locale, it's using the default locale instead keeping the current locale like it should. I think those issues are connected
Edit:
- When I print the locale parameter in controller#create, I get nil. For some reason I don't have the locale parameter at all.
model file:
validate :relevant_date_time
def relevant_date_time
errors.add(:date_error, I18n.t("validations.date_error")) unless date_time_is_relevant?
end
application_controller:
before_action :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
Am I forgetting something?
Information I reviewed:
- http://guides.rubyonrails.org/i18n.html
- Access translation file (i18n) from inside rails model
- Rails 3 translations within models in production
- http://www.eq8.eu/blogs/10-translating-locales-for-rails-model-errors
- https://lingohub.com/frameworks-file-formats/rails5-i18n-ruby-on-rails/
- Change locale at runtime in Rails 3