Mobiliy gem: Adding translations to an existing model (that already has a lot of records)?

495 views Asked by At

What's the easiest way to add translation capabilities to an existing model and automatically migrate the existing records?

The globalize gem provides a method create_translation_table with an option migrate_data: true, is there an equivalent for mobility?

1

There are 1 answers

0
Mahinour Elsheikh On

The only workaround I found when working with the gem using the :key_value Strategy is to create a migration for each table and re-saving the value of the column using [:column_name]

Example: If we Have a Post Table and I want to add it's name attribute to translations: The Mobility migration(s) must be executed and post.rb must include:

 # post.rb
class Post < ApplicationRecord
    extend Mobility
    translates :name, type: :string
end

Then update the records to reflect the value of the default language (assuming application.rb has config.i18n.default_locale = :de and initializers/mobility.rb defines locale_accessors [:de, :en, :sl]

Post.all.each do |post|
  post.update(name_de: post[:name])
end

Then verify:

> Post.last.name_de
> Post.last.name_en
> Post.last.name_sl