public
Created

Print out full error messages for nested models

  • Download Gist
full_error_messages.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.