Skip to content

Instantly share code, notes, and snippets.

@chrisdarroch
Created July 17, 2010 01:20
Show Gist options
  • Save chrisdarroch/479142 to your computer and use it in GitHub Desktop.
Save chrisdarroch/479142 to your computer and use it in GitHub Desktop.
# Determines if a particular ActiveRecord model or form object has errors on it.
# The method returns:
# - false if the object doesn't respond to #errors
# - true if the array of errors on the object is not empty
# - false in all other cases.
#
# You can optionally scope the check to look for specific errors.
# - In the case of a symbol, it will return a subset of errors as returned by the ActiveRecord::Errors#on(model) method
# - In the case of a String or Regexp, The errors array will be reduced by selecting only those who have keys containing the specified string/regexp to match.
#
# Examples:
#
# <% form_for @applicants do |form| %>
# <% if errors_on?(form.object) %>
# <p>It appears there are some problems with the applicant.</p>
# <% end %>
# ...
#
#
# <% if errors_on?(@applicants.first, "phone_number") %>
# <p>Please check the phone number entered for this applicant.</p>
# <% end %>
def errors_on?(object, scope = nil)
return false unless object.respond_to? :errors
errors = case scope.class
when Symbol then object.errors.on(scope)
when Regexp then object.errors.select { |e| e.to_s =~ scope }
when String then object.errors.select { |e| e.to_s.include? scope }
else object.errors
end
return (errors.size > 0)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment