【问题标题】:Error messages in nested attribute嵌套属性中的错误消息
【发布时间】:2016-08-08 20:15:21
【问题描述】:

我有三个模型,分别称为 AccountUserAccountPermission

我在创建用户时通过AccountPermission 创建Account

但是,如果出现与 Account :name 相关的问题,系统会抛出类似下面的内容。

Account permissions account name has already been taken

所以,我只需要修复此错误消息。

我尝试将消息属性添加到我的验证中。它只是附加到实际消息。

我也尝试过语言环境。仍然只是附加

en:
  activerecord:
    errors:
      models:
        account:
          attributes:
            name:
              taken: 'bla bla'

据我在ActiveModel 中看到的。此消息的结构来自下面

ActiveModel 中的locale/en.yml

en:
  errors:
    format: "%{attribute} %{message}"

那么,有什么方法可以轻松编辑此消息吗?如果我什至删除模型名称,就足够了。

【问题讨论】:

  • 您是在问是否可以在验证失败时抛出自定义错误消息?

标签: ruby-on-rails ruby activemodel


【解决方案1】:

错误消息由错误本身和属性名称连接而成,在提供的错误中为account_permissions/account.name

您可以像这样为属性名称添加语言环境:

en:
  activerecord:
    attributes:
      account: # this is model name
        name: "Name"

en:
  activerecord:
    attributes:
      account_permissions/account:
        name: "Account name"

【讨论】:

  • 终于!太感谢了。 account_permissions/account 工作 :)
  • 拯救了我的一天。谢谢@Vasfed。你在哪里找到这个的?这是在哪里记录的?
  • @Ameen 在我的项目中遇到这个问题 - 必须通读 rails 源代码,没有找到任何文档
猜你喜欢
  • 2011-07-26
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
  • 2012-02-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
相关资源
最近更新 更多