我在模型中使用以下代码将链接插入到验证错误消息中:
class Bar < ActiveRecord::Base
has_many :foos
validate :mode_matcher
def mode_matcher
self.foos.each do |f|
errors[:base] << mode_mismatch(foo) unless foo.mode == "http"
end
end
def mode_mismatch(f)
foo_path = Rails.application.routes.url_helpers.foo_path(f)
"Foo <a href='#{foo_path}'>#{f.name}</a> has the wrong mode.".html_safe
end
它工作正常,但我知道推荐的方法是通过语言环境文件。我遇到了麻烦,因为我正在验证另一个模型的属性,因此以下操作无效:
en:
activerecord:
errors:
models:
bar:
attributes:
foo:
mode_mismatch: "Foo %{link} has the wrong mode."
正确的方法是什么?
ActiveModel在几个范围内查找验证错误。Foo
并Bar
可以共享相同的错误消息(mode_mismatch
如果包含activerecord.errors.messages
而不是)activerecord.errors.models
:
en:
activerecord:
errors:
messages:
mode_mismatch: "Foo %{link} has the wrong mode."
然后使用该语言环境字符串进行link
插值就变成了一个问题
def mode_matcher
self.foos.each do |foo|
next unless foo.mode == "http"
errors.add :base, :mode_mismatch, link: Rails.application.routes.url_helpers.foo_path(f)
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句