3

我最近开始研究一个仅限 Rails 5 API 的应用程序,我包含jsonapi-resourcesransack轻松过滤任何给定请求的结果。默认情况下,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"
}]

在此控制器中修补索引方法时,如何保持原始输出结构?

4

1 回答 1

1

尝试使用 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
end
于 2017-04-06T11:16:20.357 回答