Skip to content

Repository files navigation

<img src=“https://travis-ci.org/sideshowcoder/activerecord_translatable.png” />

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.

Add

gem"activerecord_translatable"

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.

classMyModel<ActiveRecord::Baseserialize:localestranslate:nameend

And add the column as a string

classCreateMyModel<ActiveRecord::Migrationdefchangecreate_table:my_modeldo|t|t.string:localesendendend

If you are using postgres you can also use the native postgres array

gem'activerecord-postgres-array'

To add the array to the model the migration looks like this

classCreateMyModel<ActiveRecord::Migrationdefchangecreate_table:my_modeldo|t|t.string_array:localesendendend

And the model does not need to know anything about this

classMyModel<ActiveRecord::Basetranslate:nameend

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!

About

Translatable attributes for activerecord using the I18n backend provided by rails

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages