Last active
August 29, 2015 14:26
-
-
Save Marahin/2998d17330980d6a0d6d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TL:DR - after changing the language, if user submits invalid values for Post model, the validation error is still thrown in the previous locale. | |
Extended version with code: | |
I use a button to change the I18n.locale, which also sets the locale in session[:locale]. Everything works fine, every view is translated, flash messages as well, devise views, etc. | |
The problem I stepped upon, is that the Post model validation errors, after changing the locale with the button, are still sending messages translated to the old language (everything else, flash messages, devise views, and other views are properly translated). Refreshing the site doesn't fix it. | |
E.g. | |
Model validations: | |
validates_length_of :description, :minimum => 5, :maximum => 500, :too_long => I18n.t('posts.too_long'), :too_short => I18n.t('posts.too_short') | |
Reproducing the error: | |
post = Post.new(post_params) | |
post.user_id = current_user.id | |
if post.save | |
render :json => { :status => 0, :messages => ["OK"] } | |
else | |
render :json => { :status => 1, :messages => post.errors.messages[:description] } | |
end | |
If the post doesn't save, the error is rendered in the old language. | |
Locale fragments: | |
en.yml | |
posts: | |
too_short: "The message you're trying to send is too short." | |
too_long: "The message you're trying to send is too long." | |
pl.yml | |
posts: | |
too_short: "Wiadomość którą próbujesz wysłać jest za krótka." | |
too_long: "Wiadomość którą próbujesz wysłać jest za długa." | |
POST action which is being pointed by a button, to change the locale: | |
def change_locale | |
if session[:locale] == 'pl' | |
I18n.locale = :en | |
session[:locale] = 'en' | |
else | |
I18n.locale = :pl | |
session[:locale] = 'pl' | |
end | |
end | |
And the application_controller action that keeps track of the locale: (used with a before_action filter) | |
def set_locale | |
if session[:locale] == 'pl' | |
I18n.locale = :pl | |
elsif session[:locale] == 'en' | |
I18n.locale = :en | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment