Created
February 18, 2013 14:07
-
-
Save dpickett/4977672 to your computer and use it in GitHub Desktop.
This file contains 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
#propagates association validations to their foreign keys | |
#rails makes bad assumptions about forms and foreign key validations, so validate the proper way, | |
#but allow for the ability to propagate validation errors to foreign keys | |
module ValidatesAssociatedWith | |
extend ActiveSupport::Concern | |
included do | |
class_attribute :associations_validated | |
self.associations_validated = [] | |
before_validation :flush_propagated_association_errors | |
after_validation :propagate_association_errors_to_keys | |
end | |
module ClassMethods | |
def validates_associated_with(*args) | |
self.associations_validated << args.first | |
validates_presence_of *args | |
end | |
end | |
protected | |
def purge_propagated_association_errors | |
self.each_association_validated do |association| | |
errors.delete(self.class.reflect_on_association(association).foreign_key) | |
end | |
end | |
def propagate_association_errors_to_keys | |
self.each_association_validated do |association| | |
if errors[association].present? | |
errors[association].each do |error| | |
errors.add(self.class.reflect_on_association(association).foreign_key, error) | |
end | |
end | |
end | |
end | |
def each_association_validated(&block) | |
self.class.associations_validated.each(&block) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment