Skip to content

Instantly share code, notes, and snippets.

@cmorss
Created August 19, 2016 17:58
Show Gist options
  • Save cmorss/12f0b5202804eec42a663bb972e473ec to your computer and use it in GitHub Desktop.
Save cmorss/12f0b5202804eec42a663bb972e473ec to your computer and use it in GitHub Desktop.
module PullUpErrors
extend ActiveSupport::Concern
# Used to pull up errors that are on an associated collection or object
included do
after_validation :pull_up_errors
def pull_up_errors(*attrs)
@pull_up_attrs = Array(attrs)
end
end
# after_validation:
# We want the individual validation error messages on the specified attrs to be pulled
# up to this instance's errors collection.
def pull_up_errors
@@pull_up_attrs.each do |attr|
association = self.__send__(attr)
next unless association
Array(association).each do |instance|
if instance.errors.present?
instance.errors.full_messages.each { |msg| errors.add(attr, msg) }
end
end
errors[attr].delete("is invalid")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment