Rails: store translations in database

xijo picture xijo · Aug 28, 2009 · Viewed 12.7k times · Source

I was searching for a plugin/gem solution to extend the native rails i18n for storing my translations into my database. Maybe I used the wrong search terms, but all I found was the information, that changing the backend IS actually possible and this blog entry which descripes how to write my own backend.

It's hard to imagine, that all those rails apps out there having their translations stored in yml-files or every developer wrote own backends!

Do you know working solutions for this? Storing multiline texts in yml really gets me down! ;)

Thanks and greets,

Joe

Answer

Jason picture Jason · Nov 24, 2010

i18n has built-in support for using the database as a translation backend.

Create a table using this code in a migration:

   create_table :translations do |t|
     t.string :locale
     t.string :key
     t.text   :value
     t.text   :interpolations
     t.boolean :is_proc, :default => false
   end

Then add an initializer in config/initializers/i18n.rb with contents:

   I18n.backend = I18n::Backend::ActiveRecord.new

And last... put translations in the table. Something like:

locale key      value
en     Cool     Cool
es     Cool     Frio
en     nav.Home home
es     nav.Home casa
...

As of i18n 0.5.0 I believe they moved this code out into it's own gem... I forget what that gem is called.