如何为validate方法自动设置错误消息?非单属性验证的i18n配置
好问题!当你用validate方法做跨属性或者非单属性的自定义验证时,配置i18n错误消息的思路和validates单属性验证类似,但需要结合errors.add的用法来调整,下面分两种场景详细说:
1. 手动配置自定义i18n消息键
首先在模型的自定义验证方法里,调用errors.add时明确指定消息的i18n键,你可以把错误关联到:base(代表整个模型的错误,不属于某个特定属性),也可以关联到某个具体属性上,看你的需求:
模型代码示例
class Foo < ApplicationRecord # 注册自定义验证方法 validate :both_attributes_cant_be_blank private def both_attributes_cant_be_blank # 假设我们要检查两个属性不能同时为空 if some_attribute.blank? && another_attribute.blank? # 把错误关联到整个模型(:base),并指定消息键为:both_blank errors.add(:base, :both_blank) # 如果你想把错误关联到某个具体属性,比如some_attribute,就这么写: # errors.add(:some_attribute, :depends_on_another) end end end
对应的i18n本地化文件(en.yml)
根据你错误关联的对象不同,消息的配置路径也不一样:
en: activerecord: errors: models: foo: # 关联到:base的错误消息 base: both_blank: "Some attribute and another attribute can't both be empty!" # 关联到特定属性的错误消息(如果用了上面注释的写法) attributes: some_attribute: depends_on_another: "Can't be empty if another attribute is also empty!"
2. 让validate方法自动匹配i18n消息
如果你不想每次都手动指定消息键,可以利用Rails的i18n查找逻辑,让它自动关联你的验证方法名。具体做法是:
模型代码示例
把自定义验证方法的名字作为消息键传给errors.add:
class Foo < ApplicationRecord validate :both_attributes_cant_be_blank private def both_attributes_cant_be_blank if some_attribute.blank? && another_attribute.blank? # 直接用验证方法名作为消息键 errors.add(:base, :both_attributes_cant_be_blank) end end end
对应的i18n本地化文件(en.yml)
然后在对应路径下配置和方法名同名的消息即可:
en: activerecord: errors: models: foo: base: both_attributes_cant_be_blank: "Some attribute and another attribute can't both be empty!"
这样一来,Rails就会自动找到对应的本地化消息,不用每次都手动写键名啦。
内容的提问来源于stack exchange,提问作者sawa
相关产品推荐
相关产品推荐

