I have a rails project that needs to be multi-lingual. I ran into a few issues while enabling globalize for my rails project.
I was wondering if there is a thorough checklist / recipe for enabling internationalisation for a rails app.
Please note that I use ActiveAdmin which needs to be part of this as well.
Set the locales you wish to support in your config/application.rb
:
config.i18n.available_locales = [:de, :en]
Add migrations like described in the Globalize Readme
Make sure to remove NOT NULL
constraints on columns that you're translating since they will be migrated over to the new translations table:
change_column :categories, :title, :string, null: true
Detect the language based on the HTTP Accept Language Header:
application_controller.rb
# ...
def set_locale
I18n.locale = extract_locale
end
def extract_locale
headers = request.env['HTTP_ACCEPT_LANGUAGE'] || 'de'
case headers.scan(/^[a-z]{2}/).first
when 'en'
'en'
else
'de'
end
end
''
translationsGlobalize provides a fallback mechanism for missing translations. I was a bit surprised that some values didn't have a fallback on my front end. This was caused by blank values. To fix this I had to add the option fallbacks_for_empty_translations: true
for the translates
method call:
translates :title, :description, fallbacks_for_empty_translations: true
Note: This option can also used for the active_admin_translates
method call.
Scopes that use the translated fields have to be changed as well:
default_scope -> { order :title }
becomes:
default_scope -> { order('category_translations.title').includes(:translations) }
There is a gem that supports Globalize as well as ActiveAdmin:
# For Rails 4 use the master branch from github
gem "activeadmin-globalize", github: 'stefanoverna/activeadmin-globalize', branch: 'master'
Filters for translated attributes will no longer work by default:
filter :title
Will have to be changed to:
# as: :string is required otherwise the filter won't be shown
filter :translations_name, as: :string
While the following works for translated columns:
# Admin: Categories.rb
index do
column :title
end
As soon as we want to sort, there is an error, because the column title
is not in the DB.
Update I only had this on certain models and it is not clear to me when this fails. So for some models I had to disable sorting:
column :title, sortable: false