Setting locale on a per-user basis when using devi

2019-04-02 17:45发布

问题:

I have just been through one of my apps converting the authentication from authlogic to devise. 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.

With Devise, all the controllers are automatically setup, which is great. 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.

Is there an easier way of specifying some code to be run on a successful devise authentication?

回答1:

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

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


回答2:

Have you executed 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 is locale aware, which means that your views should automatically load language translations for you.

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.

The Devise wiki has a bunch of locale translations that have been provided to save you some work:

https://github.com/plataformatec/devise/wiki/I18n