Ruby on rails Ruby FastJsonAPI动态集\ U类型?

Ruby on rails Ruby FastJsonAPI动态集\ U类型?,ruby-on-rails,ruby,rails-api,fastjsonapi,Ruby On Rails,Ruby,Rails Api,Fastjsonapi,我一直在挖。效果很好 是否可以根据每个对象设置set\u type i、 我正在使用Rails STI(单表继承)。我有一组混合的基本对象和派生对象,我希望每个对象都有不同的类型 这是一个假JSON输出示例,我想: { "data": [ { "attributes": { "title": "Generic Vehicle" }, "id": "1", "type": "vehicle" }, {

我一直在挖。效果很好

是否可以根据每个对象设置
set\u type

i、 我正在使用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"
    }
  ]
}
当然,我有一个object
type
属性可以使用,因为我使用的是STI。但我不想将其用作属性:我想将其用作外部
类型
,就像上面的JSON一样

序列化程序:


这在FastJsonAPI的第1版中是不可能的,我在这里使用的是它。截至(尽管我还没有测试过)。

我也有STI,希望在渲染不同类的集合时使用适当的
类型。最后,我使用了一个自定义序列化程序来覆盖\u集合的
哈希\u
。在该方法中,可以查找特定的集合项序列化程序并调用其
记录\u散列

这比fast_jsonapi/jsonapi序列化程序实现要慢一点,但现在
数据
集合中的每个项都有适当的
类型

class MixedCollectionSerializerdata Hi@allanberry,你能给我看看你的
序列化程序吗?@fongfan999完成了!:)谢谢你的关注。你能举个例子吗?就我所知,还没有对第一级多态性的支持,只支持关系。你可能是对的。我已经有一段时间没有研究过这个问题了,也有一段时间没有使用Rails了。如果你找到了解决方案,请ping这个线程,好吗?谢谢
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
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