我一直在认真研究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
你能举个例子吗?据我所知,仍然不支持一级多态性,仅支持关系。
你可能是对的。我已经有一段时间没有对此进行研究了,并且有一段时间没有使用Rails了。如果找到解决方案,请ping此线程,好吗?谢谢。