-
Notifications
You must be signed in to change notification settings - Fork 93
Custom Error Messages
cypriss edited this page Oct 28, 2012
·
3 revisions
When there's a validation error, you get back an ErrorHash. You can get messages from it like this:
# Didn't pass required field 'email', and newsletter_subscribe is the wrong format:
outcome = UserSignup.run(name: "Bob", newsletter_subscribe: "Wat")
unless outcome.success?
outcome.errors.symbolic # => {email: :required, newsletter_subscribe: :boolean}
outcome.errors.message # => {email: "Email is required", newsletter_subscribe: "Newsletter Subscription isn't a boolean"}
outcome.errors.message_list # => ["Email is required", "Newsletter Subscription isn't a boolean"]
end
If you want to supply new default error messages (eg, do I18n), you can supply your own message generator. It's really easy. In a file such as an initializer, create something that responds to #message and pass it to Mutations.error_message_creator:
class YourClassThatCreatesErrorMessages
# key: the name of the field, eg, :email. Could be nil if it's an array element
# error_symbol: the validation symbol, eg, :matches or :required
# options:
# :index -- index of error if it's in an array
def message(key, error_symbol, options = {})
# return a string here. Eg, do your own lookup based on error_symbol.
end
end
Mutations.error_message_creator = YourClassThatCreatesErrorMessages.new