Using Ransack in a Rails 5 API Application
I recently started working on a Rails 5 API application and I have included jsonapi-resources
as well ransack
to easily filter the results for any given query. jsonapi-resources
Provides basic CRUD functionality by default , 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
JSON to generate output, which means the output has changed from:
# ORIGINAL OUTPUT STRUCTURE
{"data": [
{
"id": "3881",
"type": "cars",
"links": {
"self": ...
},
"attributes": {
...
}
}]
}
For default Rails JSON output:
[{
"id": "3881",
"attr_1": "some value",
"attr_2": "some other value"
}]
How do I keep the original output structure while fixing the index method in this controller?
source to share
Try using gem https://github.com/tiagopog/jsonapi-utils . In your case, the problem will be solved like this:
class CarsController < JSONAPI::ResourceController
include JSONAPI::Utils
def index
@cars = Car.ransack(params[:q]).result
jsonapi_render json: @cars
end
end
source to share