Skip to content
Roni Helminen edited this page Jan 9, 2022 · 10 revisions

The container backend is a new backend available as of version 0.4.x, which stores all translations for a model on a single json/jsonb column, defaulting to the translations column. See this PR and this blog post for background.

To use this backends, you will need to first add a column (named translations) to each translated model.

Setup

Rails/ActiveRecord

rails generate migration AddTranslationsToPosts translations:jsonb

(As of Mobility 0.5, this column can also alternatively be a json column, with mostly the same behavior.)

Once the migration is created, make sure to change the actual migration to set the default value of the column(s) to an empty jsonb object ({}), so it looks like this:

def change
  add_column :posts, :translations, :jsonb, default: {}
end

Then run the migration with rake db:migrate to add the column to your model table.

Using the backend is then as simple as setting your default backend to :container, and defining the attributes on the model:

class Post < ApplicationRecord
  extend Mobility
  translates :title, :content
end

Translated attributes title and content are now available. Mobility will now save the values of title and content in a depth-2 hash where the first level keys are locales.

Since translations are now stored in just a single database column, you can see the translations for both attributes by simply accessing the translations column:

post = Post.create(title: "foo")
post.title
#=> "foo"
post.content = "bar"
Mobility.with_locale(:ja) { post.title = "あああ" }
post.save
post = Post.first
post.translations
#=> {"en"=>{"title"=>"foo", "content"=>"bar"}, "ja"=>{"title"=>"あああ"}}

Like other backends, you can also query on these translated attributes using the i18n scope/dataset.

Post.i18n.where(title: "foo").to_sql
#=> SELECT "posts".* FROM "posts" WHERE ((("posts"."translations" -> 'en') ->  'title') = "foo")

Sequel

Mostly the same as above. Make sure to enable extensions as described in the Postgres Backends page.

Caveats

See the caveats section of the the Postgres Backends page.