Skip to content

Instantly share code, notes, and snippets.

@kouheiszk
Created July 28, 2020 04:58
Show Gist options
  • Save kouheiszk/ac6779f133b3fc8fb8bb2535f24984cd to your computer and use it in GitHub Desktop.
Save kouheiszk/ac6779f133b3fc8fb8bb2535f24984cd to your computer and use it in GitHub Desktop.
private def build_errors(contract:, error_prefix: nil)
result = {}
contract.attributes.each do |attribute_name, attribute|
key = "#{error_prefix}#{attribute_name}"
errors = contract.errors.full_messages_for(attribute_name)
result[key] = errors if errors.present?
if attribute.kind_of?(Array)
attribute.each.with_index do |child_contract, i|
child_errors = build_errors(contract: child_contract, error_prefix: "#{key}[#{i}].")
result.merge!(child_errors)
end
end
end
(contract.errors.keys.map(&:to_s) - result.keys - contract.attributes.keys).each do |key|
errors = contract.errors.full_messages_for(key)
result[key] = errors if errors.present?
end
result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment