Create a gist now

Instantly share code, notes, and snippets.

Print out full error messages for nested models
module FullErrorMessages
extend ActiveSupport::Concern
# includes errors on this model as well as any nested models
def all_error_messages
messages = self.errors.messages.dup
messages.each do |column, errors|
if self.respond_to?(:"#{column}_attributes=") && (resource = self.send(column))
messages[column] = resource.errors.messages
end
end
end
# this is the goodness:
#1.9.3-p362 :008 > s.all_full_error_messages
# => ["Purchaser can't be blank", "Consumer email can't be blank", "Consumer email is invalid", "Consumer full name can't be blank"]
#
# this is what we're avoiding:
#1.9.3-p362 :009 > s.errors.full_messages
# => ["Purchaser can't be blank", "Consumer is invalid"]
def all_full_error_messages
# this would properly done with full recursion, right now we're limited to a single level
formatter = self.errors.method(:full_message)
self.all_error_messages.map do |attribute, messages|
if messages.is_a? Hash
messages.map { |nested_attribute, messages| messages.map { |message| formatter.call("#{attribute} #{nested_attribute}", message) } }
else
messages.map { |message| formatter.call(attribute, message) }
end
end.flatten
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment