nuxxxx
nuxxxx

Reputation: 223

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?

Upvotes: 7

Views: 1467

Answers (2)

Igor Ivancha
Igor Ivancha

Reputation: 3451

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 %>

Upvotes: 2

spickermann
spickermann

Reputation: 106782

I think you need to define the constraint on the locale more explicit:

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

Upvotes: 0

Related Questions