Change locale at runtime in Rails 3

a 夏天 提交于 2020-01-23 03:21:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!