设计:从用户模型获取并设置区域设置 [英] Devise: fetch and set locale from User model

查看:62
本文介绍了设计:从用户模型获取并设置区域设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在User表中为每个用户设置了语言环境。我遵循了这些指令在用户登录后获取语言环境。直到用户重新加载浏览器,然后标准语言环境(en)再次变为活动状态为止,此方法一直有效。如何在会话中保留user.locale的值?我正在使用Rails_Admin,这意味着虽然我有一个User模型,但没有该User模型的控制器。

I set the locale for every user in the User table. I followed these instructions to fetch the locale after the user logs in. It works until the user reloads the browser, then the standard locale (en) becomes active again. How can I keep the value of user.locale in the session? I'm using Rails_Admin, which means whilst I do have a User model, I don't have controller for the User model.

 # 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 获取用户语言环境的方法(并使会话保持整洁)

While putting it in the session is a valid answer, you can use the current_user method to get the user's locale (and keep your session a tad cleaner)

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

这篇关于设计:从用户模型获取并设置区域设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆