ste*_*och 5 validation ruby-on-rails rails-i18n rails-activerecord
我在模型中使用以下代码将链接插入到验证错误消息中:
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
Run Code Online (Sandbox Code Playgroud)
它工作得很好,但我知道推荐的方法是通过区域设置文件。我遇到了麻烦,因为我正在验证另一个模型的属性,所以以下内容不起作用:
en:
activerecord:
errors:
models:
bar:
attributes:
foo:
mode_mismatch: "Foo %{link} has the wrong mode."
Run Code Online (Sandbox Code Playgroud)
这样做的正确方法是什么?
ActiveModel 在多个范围内查找验证错误。如果您将其包含在而不是以下位置,Foo则Bar可以共享相同的错误消息:mode_mismatchactiverecord.errors.messagesactiverecord.errors.models
en:
activerecord:
errors:
messages:
mode_mismatch: "Foo %{link} has the wrong mode."
Run Code Online (Sandbox Code Playgroud)
使用带有插值的区域设置字符串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
Run Code Online (Sandbox Code Playgroud)