【问题标题】:Why is validation being skipped?为什么会跳过验证?
【发布时间】:2020-05-15 02:59:01
【问题描述】:

我有一封电子邮件ActiveRecord(子类,不同的 PG DB)具有以下验证:

class Email < DbRecord
  belongs_to :user

  attr_accessor :skip_validation
  alias_method :skip_validation?, :skip_validation

  validates :value,
            presence: true,
            uniqueness: true,
            format: {
              with: URI::MailTo::EMAIL_REGEXP,
              message: "is an invalid email address",
              allow_blank: true,
            },
            unless: :skip_validation?

  before_validation { |record| record.value = record.value&.downcase }

skip_validation 为零。没有其他实例方法。

当没有user_id 时,验证按预期工作。

> e = Email.new(value: "foo@bar")
=> #<Email id: nil, user_id: nil, value: "foo@bar">

> e.valid?
=> false

当有 user_id 时,虚假电子邮件不会触发验证。

> e = Email.new(user_id: 7, value: "foo@bar")
=> #<Email id: nil, user_id: 7, value: "foo@bar">

> e.valid?
=> true

请注意,在 belongs_to 上设置 validate: true 没有帮助:

class Email < DbRecord
  belongs_to :user, validate: true

仍然存在:

> e = Email.new(user_id: 7, value: "foo@bar")
=> #<Email id: nil, user_id: 7, value: "foo@bar">

> e.valid?
=> true

这是为什么呢?我还应该看什么/寻找什么?

【问题讨论】:

    标签: ruby ruby-on-rails-5


    【解决方案1】:

    两步回答:

    1. "foo@bar" 是根据URI::MailTo::EMAIL_REGEXP 的有效电子邮件...

    我什至不能,但是others have hit the same issue 所以...

    我总是告诉其他人:检查你的假设。我假设验证失败是因为电子邮件地址,在我睡眠不足的状态下,我没有验证错误。

    那为什么验证失败?

    1. Rails 5 更改了 belongs_to 以强制相关 ID,因此为了使其有意义(在我的用例中),我还需要添加:
      belongs_to :user, optional: true
    

    在验证期间返回预期的错误消息。

    【讨论】:

      猜你喜欢
      • 2013-04-04
      • 2018-05-07
      • 1970-01-01
      • 2016-07-13
      • 2017-11-10
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多