Hello, dear!
I am writing a website, and there is a need for its internationalization. I did everything as written on rusrails.ru , but the language changes only when I change the locale parameter from en to ru in the address bar of the GET. I also need to link to another language in the corner of the page.
A bit of surfing the Internet found a post on stackoverflow.com , here's the link - Change locale at runtime in Rails 3 .
Following this example, I made several methods in my controllers:
ApplicationController.rb
before_filter :set_locale def set_locale if current_user I18n.locale = current_user.locale else I18n.locale = params[:locale] || I18n.default_locale end end
UsersController.rb
def change_locale locale = params[:locale] raise 'unsupported locale' unless ['ru', 'en' ].include?(locale) if current_user current_user.locale = locale current_user.save end I18n.locale = locale redirect_to :index end
In the view, I call the method like this:
<%= link_to "English", :controller => 'users', :action => 'change_locale', :locale => 'en' %>
Everything seems to be logical and should work, but unfortunately not everything works. When the user is not authenticated, that is, he does not log in, the link works, and the language switches perfectly, but when he logs in and tries to change the language, nothing happens. I decided to see whether the locale after the lines in the database is preserved:
if current_user current_user.locale = locale current_user.save end
and noticed that this was not happening, why I do not know.
I ask for help from the knowledgeable. Thank you in advance!