Question

I'm using Devise 3.2.2 and I want to customize error messages for my custom devise registrations controller, as suggested here. When passing in an already used email address, the (custom) controller code

if user.save
  render :json => user.as_json, :status => 201
else
  warden.custom_failure!
  render :json => user.errors, :status => 422
end

produces the following json

{"email":["has already been taken"]}

I'd like to have this error message read

{"messages": ["The email address has already been taken."]}

Unfortunately, I can't find the string "has already been taken" in the config/locales/en.yml-file (nor do I see it on GitHub). In other words, the suggested resolution is not directly applicable to the problem at hand.

Where can I find the error message in question? Is there a clean way to produce a human readable array of error messages in my custom controller?

Was it helpful?

Solution

Wow - RoR blew my mind for the n'th time. What a framework. I love it!

So, user.errors is just an ActiveModel::Errors object. Some errors are, as far as I understand, specified in the locale in the Devise gem. Others, like uniqueness of indexed fields etc. (like the email field), are provided by ActiveModel-validation. That's why I couldn't find the given error in the gem locale.

Now; the ActiveModel::Errors documentation has something pretty interesting to say. It says that there is a method, named full_messages(), that "returns all the full error messages in an array". My controller now looks like this:

if user.save
  render :json => user.as_json, :status => 201
else
  warden.custom_failure!
  render :json => { :messages => player.errors.full_messages }, :status => 422
end

That's it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top