设计:从用户模型获取并设置区域设置
问题描述:
我为用户表中的每个用户设置区域设置。我遵循这些instructions以在用户登录后获取语言环境。它一直运行,直到用户重新加载浏览器,然后标准语言环境(en)再次变为活动状态。我如何在会话中保留user.locale的值?我正在使用Rails_Admin,这意味着虽然我有一个用户模型,但我没有用户模型的控制器。设计:从用户模型获取并设置区域设置
# 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
答
我添加了一个字符串列到我的所谓用户_用户模型区域设置,然后将代码添加到应用程序控制器。允许使用存储,默认和区域设置作为参数。
迁移:
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
的效果好很多,感谢 – migu
需要注意的是,如果你有邮寄或需要的语言环境来请求/响应周期之外进行设置,你”除了ApplicationController之外,还需要设置语言环境。 –