Active Record Database: Load i18n Translations
Whenever you are working on a project using i18n Internationalization, all your translations are specified on a bunch of yml files located at db/locales/en|es. What if you wanted to load those translations into your active record database?
There’s a gem for that: i18n-active_record
First of all you need to put into your Gemfile:
gem 'i18n-active_record', git:'git://github.com/svenfuchs/i18n-active_record.git', require: 'i18n/active_record'
Then just go to your terminal bundle:
$ bundle install
Now create an active record model with the name Translation using the Rails Generator or just create the class, as you prefer.
The thing that matters is that it has the following attribute structure:
class CreateTranslations < ActiveRecord::Migration def self.up create_table "translations", :force => true do |t| t.string "locale" t.string "key" t.text "value" t.text "interpolations" t.boolean "is_proc", :default => false t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.timestamps end end def self.down drop_table :translations end end
Using this model you’ll be able to manage your translations, and add new ones as you need to do so.
To load I18n::Backend::ActiveRecord into your Rails application, create a new file in config/initializers named locale.rb.
A simple configuration for your locale.rb should look like this:
require 'i18n/backend/active_record' I18n.backend = I18n::Backend::ActiveRecord.new
if ActiveRecord::Base.connection.table_exists? 'translations' require 'i18n/backend/active_record' I18n.backend = I18n::Backend::Chain. new(I18n::Backend::ActiveRecord.new, I18n.backend) end
If for any reason you are using the Simple Backend and you want to load/reload an internationalization yml file after the active record internationalization has been loaded you can call the load_translations method:
$ rails c $ I18n.backend.load_translations
This method accepts a list of paths to different translation files.
You can use I18n.t(‘Your String’) to lookup translations in the database. or just t(‘Your String’) with I18n.backend_loadtranslations, as you wish.
You can also watch this gem’s source code from its github repo: https://github.com/svenfuchs/i18n-active_record/
Thanks for reading me!, I hope I have been of some help to you.
Follow me on twitter: @zazvick and stay in touch!.