Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locale not switching in Rails 4

My Rails App is on rails 4.0.2 and I have a problem switching translations with the locale variable and the params[:locale] from the url scheme following the official rails guide. I have a single page website at 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

The links to change the locale variables in the 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 are not switching. If I remove one of the translation files (currently for english and german) the languages switches to the remaining translation file. When I put back the other translation file and try to switch to it by changing the locale variable it never switches to the other language.

Why is my code not changing the translations?

like image 462
nuxxxx Avatar asked May 08 '15 11:05

nuxxxx


1 Answers

I had the same issues and maybe it 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

p.s.

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

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

and in config/locales/de.yml in German

in view

<%= link_to_unless_current t('languages.en'), locale: :en %>
|
<%= link_to_unless_current t('languages.de'), locale: :de %>
like image 54
Igor Ivancha Avatar answered Nov 08 '22 04:11

Igor Ivancha