设计:从用户模型中获取和设置区域设置

我在User表中为每个用户设置了区域设置。 我按照这些说明在用户登录后获取区域设置。它一直有效,直到用户重新加载浏览器,然后标准区域设置(en)再次变为活动状态。 如何在会话中保留user.locale的值? 我正在使用Rails_Admin,这意味着虽然我有一个User模型,但我没有User模型的控制器。

# ApplicationController def after_sign_in_path_for(resource_or_scope) if resource_or_scope.is_a?(User) && resource_or_scope.locale != I18n.locale I18n.locale = resource_or_scope.locale end super end 

将它放在会话中是一个有效的答案,您可以使用current_user方法获取用户的语言环境(并使您的会话更清洁)

 class ApplicationController < ActionController::Base protect_from_forgery before_filter :set_locale # get locale directly from the user model def set_locale I18n.locale = user_signed_in? ? current_user.locale.to_sym : I18n.default_locale end end 

管理将其保存在会话中,并在每次用户调用操作时从会话中检索它(ApplicationController中的before_filter):

 class ApplicationController < ActionController::Base protect_from_forgery before_filter :set_locale # get locale from session when user reloads the page # get locale of user def after_sign_in_path_for(resource_or_scope) if resource_or_scope.is_a?(User) && resource_or_scope.locale.to_sym != I18n.locale I18n.locale = resource_or_scope.locale.to_sym # no strings accepted session[:locale] = I18n.locale end super end def set_locale I18n.locale = session[:locale] end end 

我在我的User模型中添加了一个名为user_locale的字符串列,然后将代码添加到应用程序控制器中。 允许将存储,默认和区域设置用作参数。

移民:

 class AddLocaleToUser < ActiveRecord::Migration def change add_column :users, :user_locale, :string end end 

application_controller.rb:

 before_action :set_locale private def set_locale valid_locales=['en','es'] if !params[:locale].nil? && valid_locales.include?(params[:locale]) I18n.locale=params[:locale] current_user.update_attribute(:user_locale,I18n.locale) if user_signed_in? elsif user_signed_in? && valid_locales.include?(current_user.user_locale) I18n.locale=current_user.user_locale else I18n.locale=I18n.default_locale end end