Skip to content

Instantly share code, notes, and snippets.

@tdegrunt
Forked from pehrlich/full_error_messages.rb
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdegrunt/851cae2d5cacaa5d2cdf to your computer and use it in GitHub Desktop.
Save tdegrunt/851cae2d5cacaa5d2cdf to your computer and use it in GitHub Desktop.
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
@tdegrunt
Copy link
Author

tdegrunt commented Feb 8, 2015

  def all_error_messages(record)
    messages = record.errors.messages.dup
    messages.each do |column, errors|
      if record.respond_to?(:"#{column}_attributes=") && (resource = record.send(column))
        messages[column] = resource.errors.messages
      end
    end
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment