【问题标题】:How can I make the error message in a Rails 4.2 custom validator overridable?如何使 Rails 4.2 自定义验证器中的错误消息可覆盖?
【发布时间】:2017-06-14 21:35:43
【问题描述】:

我有一个自定义验证器。我希望它提供有用的默认错误消息。但是如果调用者 - 一个模型 - 使用 :message 参数来覆盖消息,我希望它能够工作。不幸的是,我似乎将我的验证消息硬编码到我的自定义验证器中,并且不知道如何使其更灵活。

自定义验证器:

class EmailnessValidator < ActiveModel::EachValidator
  EMAIL_REGEXP = /some regexp/

  def validate_each(record, attribute, value)
    return if value.blank?

    unless value.match(EMAIL_REGEXP)
      record.errors.add(attribute, I18n.translate("validators.emailness.error", attribute: attribute))
    end
  end
end

调用它的模型:

validates :email, presence: true, emailness: {
  message: I18n.translate("my_model.email.emailness.error")
}

i18n:

validators:
  emailness:
    error: "This should only be a default error message"
my_model:
  email:
    emailness:
      error: "This is the error message I want"

不幸的是,当我将它连接到控制器和视图时,我看到的错误消息是“这应该只是默认错误消息”而不是“这是我想要的错误消息”。

如何重写我的自定义验证器?

【问题讨论】:

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


    【解决方案1】:

    因为您的模型中忽略了选项 messages

    validates :email, presence: true, emailness: {
      message: I18n.translate("my_model.email.emailness.error")
    }
    

    你可以合并options来解决你的问题:

    def validate_each(record, attribute, value)
      return if value.blank?
    
      unless value.match(EMAIL_REGEXP)
        record.errors.add(attribute,
          I18n.translate("validators.emailness.error", attribute: attribute))
          options.merge!(value: value)) # merge options that you passed
      end
    end
    

    【讨论】:

    • 谢谢!事实证明,这在 guides.rubyonrails.org/active_record_validations.html 的规范验证方法的基本内容中。我只是错过了。还值得指出的是,options 不是validate_each 方法的参数,而是ActiveModel::EachValidator 的方法。
    • 顺便说一句,我最终解决这个问题的方式略有不同:record.errors.add(attribute, options[:message] || I18n.t("validators.emailness.error", attribute: attribute))
    猜你喜欢
    • 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
    相关资源
    最近更新 更多