Search code examples
ruby-on-rails-4localeactiveadminrails-i18n

Switching language (locale) in ActiveAdmin without passing a parameter


I want to be able to switch my locale in an ActiveAdmin app of mine. So far I've followed this guide on switching-locale, which actually mentions the problem I'm having:

You will notice, however, that all links keep the default locale of your app.

So in my case, once I switch the locale, the urls stay

  • localhost:3000/en/admin/users instead of
  • localhost:3000/de/admin/users

The guide also proposes a solution:

You can override this default locale by passing the locale to all _path methods.

But this seems error-prone and quite a lot of work.

So looks like ActiveAdmin uses I18n.locale once to create all the urls and does not consider changes to I18n.locale after that.

Meaning if you this in your ApplicationController:

def set_locale
  I18n.locale = params[:locale] || I18n.default_locale
end

I've tried overriding

ActiveAdmin::Helpers::Routes.default_url_options

in my ApplicationController, which did not help.

Does anyone have an idea how I could resolve this issue?

Edit:

I also set these and tried different variations of the scope method.

Routes

scope '(/:locale)', locale: /en|de/, defaults: { locale: I18n.locale }
  ActiveAdmin.routes(self)
end

ApplicationController

def default_url_options(options={})
  { locale: I18n.locale }.merge options
end

Solution

  • Ok so I've finally figured out what was going on.

    I originally followed the rails guide and set my routes.rb:

    # config/routes.rb
    scope "/:locale" do
      resources :books
    end
    

    which resulted in an error like:

    No route matches {:action=>"index", :controller=>"admin/users"} missing required keys: [:locale]

    this was "fixed" by setting

    scope ':locale', defaults: { locale: I18n.locale } do
      ActiveAdmin.routes(self)
    end
    

    as suggested in the current version of the Switching locale guide. But this has the side-effect of all subsequent url_helpers using this locale for url generation. BTW at least one other person ran into this.

    My current work-around can be found here:

     lib/active_admin/helpers/routes/url_helpers.rb
     def self.default_url_options         
        (Rails.application.config.action_mailer.default_url_options.merge({locale: ::I18n.locale})) || {}
     end
    

    Now urls are generated as expected.