4

I recently started working on a Rails 5 API only application and I included jsonapi-resources as well as ransack to easily filter the results for any given request. By default, jsonapi-resources provides basic CRUD functionality, but in order to insert the search parameters for ransack I need to overwrite the default index method in my controller:

class CarsController < JSONAPI::ResourceController

  def index
    @cars = Car.ransack(params[:q]).result
    render json: @cars
  end

end

Now, this works fine, but it no longer uses jsonapi-resources to generate the JSON output, which means the output changed from:

# ORIGINAL OUTPUT STRUCTURE
{"data": [
  {
    "id": "3881",
    "type": "cars",
    "links": {
      "self": ...
    },
    "attributes": {
      ...
    }
  }]
}

To a default Rails JSON output:

[{
  "id": "3881",
  "attr_1": "some value",
  "attr_2": "some other value"
}]

How can I keep the original output structure while patching the index method in this controller?

Severin
  • 8,508
  • 14
  • 68
  • 117

1 Answers1

2

Try to use the gem https://github.com/tiagopog/jsonapi-utils. In your case the problem will be solved in this way:

class CarsController < JSONAPI::ResourceController
  include JSONAPI::Utils

  def index
    @cars = Car.ransack(params[:q]).result
    jsonapi_render json: @cars
  end
end