Untranslated validation errors with all meta data for APIs behind Javascript frontends
The easiest way to install Rails::API::ValidationErrors
is to add it to your
Gemfile
:
gem "rails_api_validation_errors"
Then, install it on the command line:
$ bundle install
Include Rails::API::HashValidationErrors
in your API's base controller. This makes
sure that Rails will not translate error messages, but returns a hash per attribute
and error including the error key and meta information.
class API::BaseController < ApplicationController
include Rails::API::HashValidationErrors
end
To use the new error messages simply return the model's errors in JSON or XML in your controllers:
class API::PeopleController < API::BaseController
def create
@person = Person.new(person_params)
if @person.valid?
render :json => @person
else
render :json => { :errors => @person.errors }
end
end
end
This will result in the following JSON response in case of validation errors:
{
"errors": {
"name": [
{
"message": "blank",
"meta":{}
}
]
}
}