I have this custom validations that throws an “undefined method `>’ for nil:NilClass” when ever birthday is not set because birthday is nil.
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
I already have validates_presence_of for birthday so is there a way to have is_21_or_older called only after validates_presence_of passes?
Rails runs all validators independently, in order to give you an array of all the errors at once. This is done to avoid the all too common scenario:
There are two things you can do, that I know of. Either include everything under your custom validator, in which case everything is under your control, or use the
:unless => Proc.new { |x| x.birthday.nil? }modifier to explicitly restrict your validator from running under the circumstances it would break. I’d definitely suggest the first approach; the second is hacky.Maybe an even better approach is to keep the presence validator, just exit your custom validator when it sees the other validator’s condition is failed.