Skip to content

Instantly share code, notes, and snippets.

@nickjacob
Created June 19, 2016 09:19
Show Gist options
  • Save nickjacob/6c06618c72a928b74259b84a91b42d9e to your computer and use it in GitHub Desktop.
Save nickjacob/6c06618c72a928b74259b84a91b42d9e to your computer and use it in GitHub Desktop.
Monkey patch rails to output json-api compatible validation errors using respond_with

Using respond_with and json-api

ActiveModel::Serializer makes it easy to output json-api compatible models, but if you try to respond with validation errors your 422 response will not be in json-api format, which will break compatible tools (e.g., Ember adapters)

You can monkey-patch rails so that respond_with formats validation errors correctly (since ActiveModel::Error already has enough information to be useful in json-api).

Just add an initializer that overrides ActionController::Responder#json_resource_errors:

# e.g in config/initializers/action_controller_json_api.rb
ActionController::Responder.class_eval do
  def json_resource_errors
    errors = resource.errors.map do |key, error|
      {
        id: key,
        title: error,
        status: :unprocessable_entity
      }
    end

    { errors: errors }
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment