我最近开始只使用Rails 5API应用程序,我还包括了jsonapi-resources和ransack,以方便地过滤任何给定请求的结果。默认情况下,jsonapi-resources提供了基本的CRUD功能,但是为了插入ransack的搜索参数,我需要覆盖控制器中的默认索引方法:
class CarsController < JSONAPI::ResourceController
def index
@cars = Car.ransack(params[:q]).result
render json: @cars
end
end现在,这很好,但是它不再使用jsonapi-resources生成JSON输出,这意味着输出更改为:
# ORIGINAL OUTPUT STRUCTURE
{"data": [
{
"id": "3881",
"type": "cars",
"links": {
"self": ...
},
"attributes": {
...
}
}]
}到默认的Rails JSON输出:
[{
"id": "3881",
"attr_1": "some value",
"attr_2": "some other value"
}]如何在此控制器中修补索引方法时保留原有的输出结构?
发布于 2017-04-06 11:16:20
尝试使用gem https://github.com/tiagopog/jsonapi-utils。就你的情况而言,问题将以这种方式得到解决:
class CarsController < JSONAPI::ResourceController
include JSONAPI::Utils
def index
@cars = Car.ransack(params[:q]).result
jsonapi_render json: @cars
end
endhttps://stackoverflow.com/questions/42925848
复制相似问题