Skip to content

Instantly share code, notes, and snippets.

@nsmmrs
Created April 22, 2023 20:45
Show Gist options
  • Save nsmmrs/13ab7f63cdbac904a04574613e16ca88 to your computer and use it in GitHub Desktop.
Save nsmmrs/13ab7f63cdbac904a04574613e16ca88 to your computer and use it in GitHub Desktop.
Rails Validation Error Helpers
class ApplicationRecord
def add_error(attribute, type, message=nil)
attribute = attribute.to_s.to_sym
type = type.to_s.to_sym
errors.add attribute, type, message: message
end
def has_error?(attribute, type)
attribute = attribute.to_s.to_sym
type = type.to_s.to_sym
errors.details[attribute].include?(error: type)
end
end
@nsmmrs
Copy link
Author

nsmmrs commented Apr 22, 2023

These two helpers have made my life easier whenever doing a lot of validations AND needing to check for the presence of certain errors (as opposed to the usual case of just checking whether there were any errors at all).

The add_error helper isn't much different from the normal syntax, but it's nice to have complementary methods with a similar API.

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