Tag Archives: mongoid

Mongoid localize

If you’re using Mongoid and you need to translate the content of a field in multiple languages (locales) here’re the steps how to do it without additional gems by using “localize” attribute for a field. For example, here’s a simple “Page” model (rails):

class Page
  include Mongoid::Document

  field :title, type: String, localize: true, default: ""
  field :text, type: String, localize: true, default: ""

As you can see, we’ve added “localize: true” to our field definition, which means that our field will be stored with this structure:

  "title" : { "en" : "About us", "it" : "Chi siamo" },
  "text" : { "en" : "English lorem ipsum...", "it" : "Italian lorem ipsum..." }

I’ve set also the default value to an empty string because for some reason when you init a new record it’s initialized with {} ( for ex: {“en” : “{}”} ) instead as a empty string or a null value.Then in your views just print as it was a normal field, for example:


To display the field in a different language just change the locale with I18n.locale = “xx”.
The same way works also update_attributes, just pass it from the form as it was an normal field and call page.update_attributes(params[:page]) for example.