【问题标题】:Override nested attributes name using I18n使用 I18n 覆盖嵌套属性名称
【发布时间】:2015-06-02 15:25:53
【问题描述】:

我有两个模型 StoreStoreDetail 如下:

class Store
   has_one :store_detail, dependent: :destroy
end

还有StoreDetail:

class StoreDetail
   belongs_to :store, class_name: 'Store'
   belongs_to :state, class_name: 'State'
   belongs_to :city, class_name: 'City'
   belongs_to :zip_code, class_name: 'Zip Code'
end

我重写了 state 的属性如下:

attributes:
  store/store_detail:
    state: "State"
    city: "City"
    zip_code: "Zip Code"

但我收到了验证消息:

Store detail state can't be blank
Store detail city can't be blank
Store detail zip code can't be blank

我想不带“Store detail”,如下:

State can't be blank

如何覆盖嵌套属性?

【问题讨论】:

  • 我会再调查的。

标签: ruby-on-rails attributes rails-i18n


【解决方案1】:

这在 i18n 中是非常可能的:

en:
  activerecord:
    errors:
      models:
        store_detail:
          attributes:
            state:
              blank: State can't be blank.
            city:
              blank: City can't be blank.
            zip_code:
              blank: Zip code cant't be blank.

非常重要

  • 所有以“en”开头并以“models”结尾的嵌套标签必须与示例中指定的完全一致。

  • en.yml(或您正在使用的任何 kangage 文件)中的模型名称是必不可少的

  • 模型名称必须与 model.rb 匹配,因为这标识了要为 activerecord 验证的字段名称

  • 验证字段名称必须与您的 schema.rb 字段名称匹配,例如 zip_code,而不是 zip。

  • “空白:”标识符告诉 Rails activerecord 组件在特定验证失败时执行字符串替换 i18n yaml 文件中的内容。

调试 i18n(已添加)

  • 验证 YAML:如果您没有看到您定义的 en.yml 验证消息,但默认值一直显示,则您的 en.yml 出于某种原因无法正常工作。 YAML 对文件中的空格和文件中的任何尾随空格等非常挑剔。但它不会显示任何错误,它只是恢复使用 Rails 默认消息。这是一个 YAML Lint 工具:http://yaml-online-parser.appspot.com/

  • i18n 的 Rails 规范http://guides.rubyonrails.org/i18n.html

  • 调试 i18n:使用 gem i18n-tasks 创建 i18n 组件的综合报告:https://github.com/glebm/i18n-tasks

  • Application.rb:确保您已设置 i18n。

# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
  config.i18n.default_locale = :en
  config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')] 

如果您想要针对 activerecord 类型错误的自定义错误消息,您必须使用 i18n。这不是一件整洁的事情。它根本不是 DRY,但它是可用的。

【讨论】:

  • 不幸的是输出是一样的Store detail state can't be blank
  • 在我的回答中添加了关于 i18n 调试的部分。祝你好运!
【解决方案2】:

您可以使用自定义验证消息:

class StoreDetail < ActiveRecord::Base
  validates :state_id, presence: true,
  message: I18n.t(:state_cant_be_blank)
end

然后在 locales/*.yml

 en:
   state_cant_be_blank: State can't be blank

【讨论】:

  • 是的,这很好。但是 OP 想要破解 yaml 文件的方式。.. :)
  • 我需要使用 I18n,如果有嵌套属性的解决方案。
  • 我修改了我的答案以使用 I18t,请检查它是否适合你。
猜你喜欢
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
  • 2011-05-09
  • 1970-01-01
  • 2012-06-17
  • 1970-01-01
相关资源
最近更新 更多