Skip to content

Instantly share code, notes, and snippets.

@baldwindavid
Created February 27, 2013 19:19
Show Gist options
  • Save baldwindavid/5050782 to your computer and use it in GitHub Desktop.
Save baldwindavid/5050782 to your computer and use it in GitHub Desktop.
A validator that checks the presence of other related fields that should be present. It would probably always be used in conjunction with :allow_blank => true.
class DependentPresenceValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
dependents = [options[:dependents]].flatten
dependents.each do |dependent|
unless record.send(dependent).present?
record.errors.add dependent, "must not be blank when #{attribute.to_s.humanize} is present."
end
end
end
end
# example usage
class Person
validates :name,
:dependent_presence => { :dependents => [:dob, :phone] },
:allow_blank => true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment