如何使 Rails 4.2 自定义验证程序中的错误消息可覆盖?

How can I make the error message in a Rails 4.2 custom validator overridable?

我有一个自定义验证器。我希望它提供有用的默认错误消息。但是如果调用者——一个模型——使用 :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"

不幸的是,当我将其连接到控制器和视图时,我看到的错误消息是 "This should only be a default error message" 而不是 "This is the error message I want"。

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

因为选项 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