Warm tip: This article is reproduced from serverfault.com, please click

其他-Ruby FastJsonAPI动态set_type?

(其他 - Ruby FastJsonAPI dynamic set_type?)

发布于 2018-03-17 05:11:06

我一直在认真研究FastJsonAPI效果很好。

是否可以基于每个对象设置set_type 序列化程序定义

即我正在使用Rails STI(单表继承)。我有一组混合的基础对象和派生对象,并且我想为每个对象使用不同的类型。

这是我想要的JSON输出的伪造示例:

{
  "data": [
    {
      "attributes": {
        "title": "Generic Vehicle"
      },
      "id": "1",
      "type": "vehicle"
    },
    {
      "attributes": {
        "title": "Fast Car"
      },
      "id": "2",
      "type": "car"
    },
    {
      "attributes": {
        "title": "Slow Car"
      },
      "id": "3",
      "type": "car"
    },
    {
      "attributes": {
        "title": "Motorcycle"
      },
      "id": "4",
      "type": "motorcycle"
    }
  ]
}

我确实有一个type可以使用的对象属性,因为我正在使用STI。我不想将其用作属性:我想将其用作外部type,如上面的JSON所示。

序列化器:

class VehicleSerializer
  include FastJsonapi::ObjectSerializer
  set_type :vehicle  # can I tie this to individual objects, right here?
  attributes :title
end

class CarSerializer < VehicleSerializer
  set_type :car
  attributes :title
end

class MotorcycleSerializer < VehicleSerializer
  set_type :motorcycle
  attributes :title
end

class TruckSerializer < VehicleSerializer
  set_type :truck
  attributes :title
end

你会看到,我有一些仅从单个对象提取的控制器type,对于他们来说,单个CarSerializer或任何对象都可以很好地工作。问题是当我使用像这样的控制器时,该控制器在index方法中聚合了多种车辆类型:

require_relative '../serializers/serializers.rb'

class MultiVehiclesController < ApplicationController

  def index
    @vehicles = Vehicle.where(type: ["Car", "Motorcycle"])

    # perhaps there's a way to modify the following line to use a different serializer for each item in the rendered query?
    render json: VehicleSerializer.new(@vehicles).serializable_hash
  end

  def show
    @vehicle = Vehicle.find(params[:id])

    # I suppose here as well:
    render json: VehicleSerializer.new(@vehicle).serializable_hash
  end

end
Questioner
aljabear
Viewed
0
aljabear 2018-11-28 20:29:37

在我使用的FastJsonAPI版本1中这是不可能的。 现在显然是有可能1.2版本(虽然我还没有测试过)。