Column Backend

Chris Salzberg edited this page Mar 24, 2018 · 9 revisions

The Column backend stores translations as columns on the model table, with a suffix for the locale.

A detailed description of this backend is provided as "Strategy #1" in this blog post.

Generating Translatable Columns

Although it is quite simple to add columns to the model table, there is a built-in generator to make this just a little bit easier. If your default backend is set to :column, and you want to add columns for all locales in I18n.available_locales to a model Post with attributes title (string) and content (text), here is how you would do it:

rails generate mobility:translations post title:string content:text

(Pass --backend=column as an option if your default backend is something else. Note that you must have already created the posts table for this generator to work.)

If your available locales are English, French and Japanese, this will generate a migration like this:

class CreatePostTitleAndContentTranslationsForMobilityColumnBackend < ActiveRecord::Migration[5.0]
  def change
    add_column :posts, :title_en, :string
    add_column :posts, :title_fr, :string
    add_column :posts, :title_ja, :string
    add_column :posts, :content_en, :text
    add_column :posts, :content_fr, :text
    add_column :posts, :content_ja, :text
  end
end

If you want indexes for these columns (recommended), just pass e.g. title:string:index to the generator and indexes will be added for title_en, title_fr and title_ja.

Later, if you add new locales to your application (to I18n.available_locales) you can add necessary columns by re-running the generator as above with the attribute names. Mobility will only include add_column calls in the migration for columns (locale + attribute) which are missing.

Querying

Querying works like you would expect, using the i18n scope:

Post.i18n.find_by(foo: "fooval", bar: "barval")
#=> SELECT  "posts".* FROM "posts" WHERE "posts"."foo_en" = "fooval" AND "posts"."bar_en" = "barval" LIMIT 1
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.