Skip to content

Instantly share code, notes, and snippets.

@nickjacob
Created June 19, 2016 09:19
Show Gist options
  • Select an option

  • Save nickjacob/6c06618c72a928b74259b84a91b42d9e to your computer and use it in GitHub Desktop.

Select an option

Save nickjacob/6c06618c72a928b74259b84a91b42d9e to your computer and use it in GitHub Desktop.

Revisions

  1. Nick Jacob created this gist Jun 19, 2016.
    25 changes: 25 additions & 0 deletions json-api-rails-errors.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    # Using `respond_with` and json-api

    [ActiveModel::Serializer](https://github.com/rails-api/active_model_serializers) 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`:

    ```ruby
    # 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
    ```