Locale doesn't switch in Rails 4

My Rails application is on rails 4.0.2, and I have the problem of switching translations with the variable locale and params[:locale] from the URL scheme following the official guide rails. I have a one page site on my site .

My routes for internationalization:

 scope "(:locale)", locale: /en|de/ do #my routes here end 

My application controller

 before_filter :set_locale def set_locale I18n.locale = params[:locale] || I18n.default_locale #Rails.application.routes.default_url_options[:locale]= I18n.locale end # app/controllers/application_controller.rb def default_url_options(options = {}) { locale: I18n.locale }.merge options end 

Links for changing locale variables in a view:

 <%= link_to_unless I18n.locale == :en, "English", locale: :en %> | <%= link_to_unless I18n.locale == :de, "Deutsch", locale: :de %> 

What happens: the locale variable is set correctly, but the translations do not switch. If I delete one of the translation files (currently for English and German), the languages ​​switch to the remaining translation file. When I return another translation file and try to switch to it by changing the locale variable, it never switches to another language.

Why doesn't my code change translations?

+6
source share
2 answers

I had the same problems, and maybe this would be a solution for you:

in routes.rb change

 scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do #your routes here end get '*path', to: redirect("/#{I18n.default_locale}/%{path}") get '', to: redirect("/#{I18n.default_locale}") 

in application_controller.rb

 def set_locale I18n.locale = params[:locale] if params[:locale].present? end def default_url_options(options = {}) {locale: I18n.locale} end 

ps

in config/locales/en.yml something like this:

 en: languages: en: "English" de: "Deutsch" 

and config/locales/de.yml in German

in sight

 <%= link_to_unless_current t('languages.en'), locale: :en %> | <%= link_to_unless_current t('languages.de'), locale: :de %> 
+2
source

I think you need to more strictly define the locale constraint:

 scope path: '(:locale)', constraints: { locale: /en|de/ } do # routes you want to localize end 
0
source

Source: https://habr.com/ru/post/986818/


All Articles