Rails: Switch locale in descendant of Devise controller
Problem
I have this class-inheritance set up with switching to a Dutch locale (according to https://guides.rubyonrails.org/i18n.html, May 20, 2020):
class Api::DeviseSessionsController < Devise::SessionsController
around_action :switch_locale
private def switch_locale(&action)
I18n.with_locale('nl-NL', &action)
endBut unfortunately some Devise error messages, especially the login errors, are still using the English locale.
Solution
In ApplicationController:
before_action :set_locale
private def set_locale
if (self.class < ::DeviseController)
I18n.locale = 'nl-NL'
end
endNow I get my error messages in Dutch, e.g. "Ongeldig e-mail adres of wachtwoord" :)
Journal
20200522
Got this error:
ArgumentError (A copy of ApplicationController has been removed from the module tree but is still active!)
Solution: Prefix Devise constant with double colon (::) to define it as a top-level constant.
If that doesn't work, changing the 'parent_controller' to a MyDeviseController of our own with proper I18n, in config/initializers/devise.rb might be a workaround:
# ==> Controller configuration
# Configure the parent class to the devise controllers.
# config.parent_controller = 'DeviseController'20200520
Putting this in ApplicationController might also work, but somehow my Vue-application behaves differently and causes yet another, some kind of 404-error:
around_action :switch_locale
private def switch_locale(&action)
if (self.class < DeviseController)
I18n.with_locale('nl-NL', &action)
end
endso I'll stick to the 'before_action' for now.