问题
I am working on a rails 3 app which has different languages in my locales folder. The files are en.yml, pu.yml, sp.yml. All languages have to be converted to their various format and I need help in making users chose any language of their choice with a link like
<%= link_to "English language", ...%> <%= link_to "spanish", ...%>
When a user choses a language, the language is set as the user's preferred language so that the user does not have to keep selecting a language after each login.
回答1:
Adding to ream88's answer:
<%= link_to "spanish", :controller => 'locale', :action => 'set', :id => 'es' %>
In the LocaleController (or any other controller)
def set
locale = params[:id]
raise 'unsupported locale' unless ['es', 'en', ... ].include?(locale)
current_user.locale = locale
current_user.save
redirect_to :back
end
回答2:
Just add a locale
string attribute to your User
model, and make a before_filter
in your application_controller.rb
like so:
before_filter :set_locale
...
def set_locale
I18n.locale = current_user.locale if current_user
end
More infos at Rails Internationalization (I18n) API!
来源:https://stackoverflow.com/questions/6822440/change-locale-at-runtime-in-rails-3