Configuring Rails Admin with i18n for Multilingual Support

Configuring your Rails application with internationalization (i18n) for multilingual support can be a bit tricky. If you want to enable support for languages like Spanish (esp), Nepali (np), Hindi (hi), Mexican Spanish (mx), and others, follow these steps:

1. Configure your routes.rb

You need to adjust your routes.rb file to include locale information in your URLs. This ensures that Rails Admin and your application recognize the desired language.

# config/routes.rb
scope "(:locale)", locale: /en|np|hi|mx/ do
  mount RailsAdmin::Engine => '/admin', as: 'rails_admin'

  devise_for :users
  root 'home#index'
  resource :dashboard do
    collection do
      get :report
    end
  end
end

2. Set the Locale for Each Request

Set the locale for each incoming request to ensure that your application displays content in the selected language.

# config/initializers/rails_admin.rb
RailsAdmin.config do |config|

  ### Popular gems integration

  ## == Devise ==
  config.authenticate_with do
    default_locale = :np  # Set your default locale here

    # Set the locale per request
    I18n.locale = params[:locale] || default_locale

    if current_user.blank? || !current_user.has_role?('super_admin')
      flash[:error] = 'You are not authorized to access this resource.'
      redirect_to '/'
    end
  end

  config.current_user_method(&:current_user)
end

3. Copy the YML File to Your Project

Copy the necessary YML language file to your project. This file contains translations for Rails Admin.

You can find the English YML file at .rvm/gems/ruby-2.6.3/gems/rails_admin-1.4.2/config/locales/rails_admin.en.yml. Copy it to /config/locales/rails_admin.np.yml or rails_admin.[your_locale].yml according to your chosen locale.

Make sure to adjust the content of the YML file to match your chosen locale.

4. Handling Common Error

If you encounter a “translation missing” error, specifically translation missing for np.datetime.distance_in_words.x_days, you can fix it by adding the following translation to your rails_admin.np.yml file:

np:
  datetime:
    distance_in_words:
      x_days: "%{count} दिन"
      about_x_hours: "%{count} घण्टा"

Alternatively, you can copy this YML file to the config/locale folder for Nepali translations.

GitHub Gist for Nepali Translations

By following these steps, you’ll configure your Rails Admin application to support internationalization, making it accessible to users in various languages.