我一直在挖掘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。但我不想将其用作属性:我想将其用作 outside 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