Rails I18n通过数据库列 [英] Rails I18n via database column

查看:83
本文介绍了Rails I18n通过数据库列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个遗留数据库表,该表具有name_en和name_es列,并且想知道在ActiveRecord中基于用户的i18n偏好查询这两种翻译的最佳方法是什么.

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_enname_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆