Created
April 22, 2023 20:45
-
-
Save nsmmrs/13ab7f63cdbac904a04574613e16ca88 to your computer and use it in GitHub Desktop.
Rails Validation Error Helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.