localized fields

From 2.4.0 Mongoid now supports localized fields without the need of any external gem.

class Product
  include Mongoid::Document
  field :description, localize: true
end

By telling the field to localize, Mongoid will under the covers store the field as a hash of locale/value pairs, but normal access to it will behave like a string.

# Using a default locale of en.
product = Product.new
product.description = "Marvelous!"
I18n.locale = :de
product.description = "Fantastisch!"

product.attributes
#=> { "description" => { "en" => "Marvelous!", "de" => "Fantastisch!" }

You can get and set all the translations at once by using the corresponding _translations method.

product.description_translations
#=> { "description" => { "en" => "Marvelous!", "de" => "Fantastisch!" }
product.description_translations =
  { "description" => { "en" => "Marvelous!", "de" => "Wunderbar!" }

fallbacks

When using fallbacks, Mongoid will automatically use them when a translation is not available.

For Rails applications, set the fallbacks configuration setting to true in your environment.

config.i18n.fallbacks = true

For non-rails applications, you must include the fallbacks module straight to the I18n gem.

require "i18n/backend/fallbacks"
I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)

Then when the fallbacks are defined, if a translation is not present Mongoid will fallback in order of the defined locales.

# Using a default locale of en.
::I18n.fallbacks[:de] = [ :de, :en, :es ]
product = Product.new
product.description = "Marvelous!"
I18n.locale = :de
product.description #=> "Marvelous!"

querying

When querying for localized fields using Mongoid's criteria API, Mongoid will automatically alter the criteria to match the current locale.

mongoid
# Match all prodcucts with Marvelous as the description. Locale is en.
Product.where(description: "Marvelous!")
mongodb query selector
{ "description.en" : "Marvelous!" }

indexing

If you plan to be querying extensively on localized fields, you should index each of the locales that you plan on searching on.

class Product
  include Mongoid::Document
  field :description, localize: true

  index "description.de"
  index "description.en"
end

validation

Mongoid's presence validator will make sure that translations are present for all locales that are in the underlying hash.