我该在哪里找到Rails错误信息的键列表?

9

我试图通过修改en.yml来自定义我的错误消息。

注:该句子涉及IT技术,指用户想通过修改一个文件来实现自定义错误消息。
en:
  errors:
    messages:
      blank: "This is a required field."

现在,每个具有“validates presence: true”验证器的空字段都会显示这条新消息。

我想找到一份消息类型列表以进行修改。例如,我如何自定义“numericality”验证器消息?或者“greater_than”验证器?

有什么建议可以找到这个列表吗?

4个回答

15
以下是en.yml文件中您可以自定义的消息列表:
validates_acceptance_of
`:accepted` (“must be accepted”)
validates_associated
`:invalid` (“is invalid”)
validates_confirmation_of
`:confirmation` (“doesn’t match confirmation”)
validates_exclusion_of
`:exclusion` (“is reserved”)
validates_format_of
`:invalid` (“is invalid”)
validates_inclusion_of
`:inclusion`(“is not included in the list”)
validates_length_of
`:too_short` (“is too short (minimum is {{count}} characters)”)
`:too_long` (“is too long (maximum is {{count}} characters)”)
validates_length_of (with :is option)
`:wrong_length` (“is the wrong length (should be {{count}} characters)”)
validates_numericality_of
`:not_a_number` (“is not a number”)
validates_numericality_of (with :odd option)
`:odd` (“must be odd”)
validates_numericality_of (with :even option)
`:even` (“must be even”)
validates_numericality_of (with :greater_than option)
`:greater_than` (“must be greater than {{count}}”)
validates_numericality_of (with :greater_than_or_equal_to option)
`:greater_than_or_equal_to` (“must be greater than or equal to {{count}}”)
validates_numericality_of (with :equal_to option)
`:equal_to` (“must be equal to {{count}}”)
validates_numericality_of (with :less_than option)
`:less_than` (“must be less than {{count}}”)
validates_numericality_of (with :less_than_or_equal_to option)
`:less_than_or_equal_to` (“must be less than or equal to {{count}}”)
validates_presence_of
`:blank` (“can’t be blank”)
validates_uniqueness_of
`:taken` (“has already been taken”)

4
有什么建议在哪里找到这个? - Brad Werth

8

0

它在一系列的命名空间中查找错误消息。考虑一个具有名称属性验证的用户模型,如下所示:

class User < ActiveRecord::Base
  validates :name, presence: true
end

在这种情况下,错误消息的关键是:blank。Active Record将在以下命名空间中查找此关键字:
activerecord.errors.models.[model_name].attributes.[attribute_name]
activerecord.errors.models.[model_name]
activerecord.errors.messages
errors.attributes.[attribute_name]
errors.messages

因此,在我们的示例中,它将按照以下顺序尝试这些密钥,并返回第一个结果:
activerecord.errors.models.user.attributes.name.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
errors.attributes.name.blank
errors.messages.blank

希望能有所帮助。谢谢。

0
补充一下@MikeL的答案,他只展示了键,完整的列表包括键和插值消息可以在Rails自己的Github存储库这里找到。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接