我有一封电子邮件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
请注意,在validate: true
上设置belongs_to
无效:
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
为什么?我还要看/找什么?
两步回答:
"foo@bar"
是根据URI::MailTo::EMAIL_REGEXP
...的有效电子邮件我什至不能,但others have hit the same issue如此...
正如我总是告诉其他所有人:检查您的假设。我假定由于电子邮件地址,验证失败,并且在我的睡眠剥夺状态下,我没有验证错误。
那么,为什么验证失败?
belongs_to
以使相关ID成为强制性,因此(在我的用例中)为了使其有意义,我还需要添加: belongs_to :user, optional: true
在验证过程中返回预期的错误消息。