[英]Setting locale on a per-user basis when using devise and rails 3
I have just been through one of my apps converting the authentication from authlogic to devise. 我刚刚通过我的一个应用程序将身份验证从authlogic转换为设计。 By and large this has been amazingly straight-forward to do but there is one issue I can't find an easy fix for. 总的来说,这是非常简单的事情,但是有一个我找不到容易解决的问题。
In the app, the user has the option of choosing their locale. 在应用程序中,用户可以选择其区域设置。 Then whenever they login, they view the app in the language they choose. 然后,每当他们登录时,他们都会以他们选择的语言查看该应用程序。 Previously, I did this by simply setting the locale in the create method of my UserSessions controller. 以前,我只需在UserSessions控制器的create方法中设置区域设置即可。
With Devise, all the controllers are automatically setup, which is great. 使用Devise,所有控制器都可以自动设置,这很棒。 I know that I could create a custom Controller that extends the DeviseController and do it like this but, from what I understand, that means that I will also need to create all the views to go with it which seems a bit over the top when I just need to run one extra line of code. 我知道我可以创建一个扩展DeviseController的自定义控制器,并按照我的理解这样做,但这意味着我还需要创建所有的视图以便在我看来有点过头了只需要运行一行额外的代码。
Is there an easier way of specifying some code to be run on a successful devise authentication? 是否有更简单的方法来指定要在成功的设计认证上运行的代码?
I found the solution I was looking for here 我找到了我在这里寻找的解决方案
As I just wanted to set the locale for the user when they logged in, all I needed was to add the following method to my ApplicationController 正如我只想为用户登录时设置区域设置一样,我需要做的就是向我的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
Have you executed rails generate devise:views
? 你有没有执行rails generate devise:views
? This will output the Devise view files for you, and then you should be able to move them to a location that matches your new extended Devise controller name. 这将为您输出Devise视图文件,然后您应该能够将它们移动到与新的扩展Devise控制器名称匹配的位置。
Devise is locale aware, which means that your views should automatically load language translations for you. Devise可以识别区域设置,这意味着您的视图应自动为您加载语言翻译。
All you need to do is provide a "devise.[:locale].yml" file in the root "locales" folder of your rails application for each language translation that you wish to support. 您需要做的就是在rails应用程序的根“locales”文件夹中为您希望支持的每种语言翻译提供“devise。[:locale] .yml”文件。
The Devise wiki has a bunch of locale translations that have been provided to save you some work: Devise Wiki提供了许多语言环境翻译,以节省您的工作:
https://github.com/plataformatec/devise/wiki/I18n https://github.com/plataformatec/devise/wiki/I18n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.