【问题标题】:Rails custom validation error messages on attributes of another modelRails 在另一个模型的属性上自定义验证错误消息
【发布时间】:2015-01-19 09:18:26
【问题描述】:

我在我的模型中使用以下代码将链接插入到验证错误消息中:

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."

这样做的正确方法是什么?

【问题讨论】:

  • 您正在使用mode_matcher 方法进行验证,但您没有在 yml 文件中指定
  • 哎呀,如果我使用mode_matcher 代替mode_mismatch,也会发生同样的事情。
  • 您是否遇到错误

标签: ruby-on-rails validation rails-activerecord rails-i18n


【解决方案1】:

ActiveModel 在多个范围内查找验证错误。 FooBar 可以为 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多