0

我有这个自定义验证,当因为生日为 nil 而没有设置生日时,它会抛出一个“未定义的方法 `>' for nil:NilClass”。

validate :is_21_or_older 
def is_21_or_older
  if birthday > 21.years.ago.to_date
    errors.add(:birthday, "Must 21 Or Older")
  end
end

我已经为生日设置了 validates_presence_of,所以有没有办法让 is_21_or_older 仅在 validates_presence_of 通过后才调用?

4

1 回答 1

3

Rails 独立运行所有验证器,以便一次为您提供所有错误的数组。这样做是为了避免太常见的情况:

请输入密码。

pass

您输入的密码无效:它不包含数字。

1234

您输入的密码无效:它不包含字母。

a1234

您输入的密码无效:密码长度至少为六个字符。

ab1234

您输入的密码无效:您不能在一个序列中使用三个或更多连续字符。

piss off

您输入的密码无效:它不包含数字。

据我所知,你可以做两件事。要么将所有内容包含在您的自定义验证器下,在这种情况下,一切都在您的控制之下,或者使用:unless => Proc.new { |x| x.birthday.nil? }修饰符明确限制您的验证器在它会中断的情况下运行。我肯定会建议第一种方法;第二个是hacky。

def is_21_or_older
  if birthday.blank?
    errors.add(:birthday, "Must have birthday")
  elsif birthday > 21.years.ago.to_date
    errors.add(:birthday, "Must 21 Or Older")
  end
end

也许更好的方法是保留存在验证器,当它看到另一个验证器的条件失败时退出您的自定义验证器。

def is_21_or_older
  return true if birthday.blank? # let the other validator handle it

  if birthday > 21.years.ago.to_date
    errors.add(:birthday, "Must 21 Or Older")
  end
end
于 2012-05-28T16:58:19.940 回答