Container Backend

Chris Salzberg edited this page Mar 24, 2018 · 9 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.

You can see the hash using read_attribute:

post = Post.create(title: "foo")
post.title
#=> "foo"
Mobility.with_locale(:ja) { post.title = "あああ" }
post.save
post = Post.first
post.read_attribute(:title)
#=> {"en"=> {"title"=>"foo"}, "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.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.