【问题标题】:How can I translate the ActiveRecord attribute name in Rails 3.2?如何翻译 Rails 3.2 中的 ActiveRecord 属性名称?
【发布时间】:2012-05-30 08:37:19
【问题描述】:

我的模型(用户)中有以下验证:

  validates :first_name,:length => {:minimum => 2,:maximum => 50},:format => { :with => /[a-zA-Z]+/ }

我的 yml 语言环境文件中有以下内容:

 attributes:
   first_name:
     too_short: "First name is too short"
     too_long: "First name is too long"
     invalid: "First name is not valid"

现在,如果我启动一个rails console,并写下以下内容:

a = User.new
a.valid?
a.errors.full_messages

我会看到以下错误:

["First name First name is too short", "First name First name is not valid"]

如您所见,属性名称也附加在字段错误之前。到目前为止,在我的代码中的任何地方,我都使用了model.errors[:field],这将始终显示我在 yml 文件中的字符串,但我想将字符串更改为:

 attributes:
   first_name:
     too_short: " is too short"
     too_long: " is too long"
     invalid: " is not valid"

并使用 full_messages 版本。问题是,我不知道如何翻译属性名称。比方说,我想而不是名字,首先有名字。我该怎么做?

【问题讨论】:

    标签: ruby-on-rails activerecord internationalization


    【解决方案1】:

    你可以在这里找到答案http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

    在您的 config/locale/(your_lang).yml 中

    en: 
      activerecord:
        models:
          user: Dude
        attributes:
          user:
            first_name: "Name first"
    

    用您需要使用的语言符号更改“en:”

    干杯

    【讨论】:

      【解决方案2】:

      在 Rails 5 中,attributes 之后,我必须在命名空间中使用下划线中的模型名称。像这样:

      pt-BR:
        activerecord:
          attributes:
            my_model_name_in_underscore: 
              attribute_name: 'String'  
      

      来源:https://stackoverflow.com/a/5526812/1290457

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多