开发者

Change locale at runtime in Rails 3

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 "span开发者_如何学运维ish", ...%>

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.


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!


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜