Created
February 27, 2013 19:19
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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