简体   繁体   中英

Ruby on Rails + Devise + I18n: how to set locale?

I use before_filter in ApplicationController to set locale for my application:

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :set_locale

  def set_locale
    I18n.locale = request.compatible_language_from ["uk", "ru", "de", "en"]
  end
end

It works for controllers that are written by me. But all devise's messages are still English.

Setting config.i18n.default_locale = "uk" (or other) in config/application.rb works, so I guess that the trouble is that devise's controller does not use my before_filter (possibly, it does not inherit ApplicationController at all (?)).

How to resolve this problem? How to make devise use my locale?

Take a look at Devise Wiki https://github.com/plataformatec/devise/wiki/I18n They have lots of YML file samples.

If you still wanna write your own, try using something like this in your I18n files

en:
  devise:
    sessions:
      signed_in: 'Signed in successfully.'

More info on GitHub https://github.com/plataformatec/devise#i18n

You need to use prepend_before_action (or prepend_before_filter but it is alias of prepend_before_action and is soon going to be deprecated) so you should have something like:

class ApplicationController < ActionController::Base
  protect_from_forgery

  prepend_before_action :set_locale

  private

  def set_locale
    I18n.locale = request.compatible_language_from [:uk, :ru, :de, :en]
  end
end

Note that this may break the I18n.locale in your views so you may need to set it in additional before_action .

I had this issue where my french devise locales were loading for everyone, and the problem was that my devise locales were originally built in their own file - devise.en.yml . I moved them into the en.yml file, and everything was fixed.

Hopefully this helps someone in the future!

You can set the default locale in config/application.rb or config/initializers/locale.rb by:

# Set default locale to something other than :en
I18n.default_locale = :fa

as suggested by the Rails Guides

Then, you should add related yml translation files like: fa.yml . The files should be located in locales dir where default en files are exist. You can also set a custom directory to be loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM