I have a simple Rails application (not even database driven). And basically I want to make it support two languages. My approach to this is to have two little flags in the footer, one of GB (for English) and one of Germany (for German). When the User clicks on one, the language of the site changes to the corresponding language of the country flag.
I have my [ en.yml ] and [ de.yml ] all setup, and I have used their keys in all my views, and I have even tested that they work by swapping the [ config.i18n.default_locale ] property between [ en ] and [ de ] in [ config/application.rb ]. All works well in that regard.
I am stuck however on how I can achieve the language changing mechanism. I have created a controller called [ Language ] and in it I have defined a method called [ Set ] but other than that, it is pretty much blank, here is what I think should happen:
class LanguageController < ApplicationController
def set
I18n.locale = params[:lang]
redirect_to(:controller => 'home', :action => 'index')
end
end
The above doesn't seem to work. When I call the [ /language/set?lang="de" ] the localized strings change to the keys not the actual German translated text.
This:
I18n.locale = params[:lang]
does not persist across requests, so when you redirect (= a new request) it reverts back to English.
You should save the language setting in a session:
class LanguageController < ApplicationController
def set
session[:lang] = params[:lang].to_sym
redirect_to(:controller => 'home', :action => 'index')
end
end
And check the session on each request. You can do this in a before_filter
in your ApplicationController
:
class ApplicationController
before_filter :set_language
def set_language
I18n.locale = session[:lang] if session[:lang]
end
end