Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
861 views
in Technique[技术] by (71.8m points)

ruby - Rails I18n via database column

I have a legacy database table that has columns name_en and name_es and was wondering what the best way to query in ActiveRecord for either translation based on the user's i18n preference would be.

The i18n implementations I see for Rails tend to be more about storing translations in a separate hash or table, but I don't want to change the structure of the database.

Currently in the old PHP app, I send an argument to the mysql query to replace the name_lang and return name_en or name_es AS name for displaying when I call the row's id.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...