Rails I18n 通过数据库列 [英] Rails I18n via database column
问题描述
我有一个包含列 name_en 和 name_es 的旧数据库表,我想知道根据用户的 i18n 偏好在 ActiveRecord 中查询任一翻译的最佳方式是什么.
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.
我看到的 Rails 的 i18n 实现更倾向于将翻译存储在单独的哈希或表中,但我不想更改数据库的结构.
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.
目前在旧的 PHP 应用程序中,我向 mysql 查询发送一个参数以替换 name_lang 并返回 name_en
或 name_es AS name
用于在我调用行 ID 时显示.
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.
推荐答案
你应该创建一个初始化器,你会在其中放置:
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
然后在你的模型中:
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
当然,我假设没有名为 name
的现有表.
Of course, I assumed there was no already existing table named name
.
这篇关于Rails I18n 通过数据库列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!