Make attributes of an ActiveRecord Model translatable, and store the translations in the provided I18n backend. This is really helpful if there already is, a interface to provide ie missing translations for elements in I18n.
to your gemfile, this should work for rails 3 and above.
Use inside of the model
class MyModel < ActiveRecord::Base translate :title end I18n.locale = :en mymodel = MyModel.create(title: "My title", title_de: "Mein Title) mymodel.title_wk = "Woohhaakkk" mymodel.title # => "My title" mymodel.title_en # => "My title" mymodel.title_wk # => "Woohhaakkk"
To save the locales ActiveRecordTranslatable saves an array of the specified locale, for this to work, the database needs the ability to save arrays. The easiest way to handle this is to use ActiveRecords ability to serialize.
class MyModel < ActiveRecord::Base serialize :locales translate :name end
And add the column as a string
class CreateMyModel < ActiveRecord::Migration def change create_table :my_model do |t| t.string :locales end end end
If you are using postgres you can also use the native postgres array
To add the array to the model the migration looks like this
class CreateMyModel < ActiveRecord::Migration def change create_table :my_model do |t| t.string_array :locales end end end
And the model does not need to know anything about this
class MyModel < ActiveRecord::Base translate :name end
How it works
Translateable saves the translation via I18n.backend.store_translations, this means that the backend has to be able to store new items. So backend needs to be for example the KeyValue or ActiveRecord one. More railscasts.com/episodes/256-i18n-backends
The tests are using rspec and an im memory sqlite database, so all that is needed is to run
$ rake spec
This has been extracted form an Rails application so it should be pretty stable by now. Any contributions and fixes are of course highly welcome!