Rails I18N via Database Column

Rails I18n via database column

You should create an initializer in which you'd put:

class ActiveRecord::Base
def self.has_translation(*attributes)
attributes.each do |attribute|
define_method "#{attribute}" do
self.send "#{attribute}_#{I18n.locale}"
end
end
end
end

Then in your models:

has_translation :name, :whatever

So that it will automatically call the proper column name depending on your current locale. In your view:

@variable.name # calling @variable.name_en if locale = :en
# @variable.name_es if locale = :es

Of course, I assumed there was no already existing table named name.

How can I display a translation of a database column name as a table heading in a view, Rails 3

You can use the static method "human_attribute_name", See the doc here on API dock

In your case:

%th= User.human_attribute_name :current_sign_in_at

(use User.human_name to display the model name translated with I18n in en.activerecord.models.user)

Hope this helps!

Rails 3 I18n for database tables

Storing translations in the db is not too bad a solution. Don't be afraid of large tables - databases are made for that! Just make sure your indexes are configured correctly and cache whatever you can.

Another, faster and possibly better solution is to use Redis as a backend for I18n. See http://guides.rubyonrails.org/i18n.html#using-different-backends and http://railscasts.com/episodes/256-i18n-backends.

Wherever you do store the translations, there's no need to try to manage the interpolations yourself as the I18n library handles this quite nicely (unless you're doing something really custom, that is).

Translating entries in the database rails

I have used globalize3 numerous times and always liked it. Maybe it can help you too.

How to internationalize content on ruby on rails?

Have you taken a look at:
http://guides.rubyonrails.org/i18n.html

It describes in some detail how to internationalise your application and

"provides an easy-to-use and extensible
framework for translating your
application to a single custom
language other than English or for
providing multi-language support in
your application."

Some useful links:

  • http://rails-i18n.org/
  • http://github.com/svenfuchs/rails-i18n
  • http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale

Update: 2018

Since answering this question nearly nine years ago, the same author of i18n has created Globalize which builds on the I18n API in Ruby on Rails to add model translations to ActiveRecord models.

Please find details here: https://github.com/globalize/globalize



Related Topics



Leave a reply



Submit