gpt4 book ai didi

ruby-on-rails - 数组中不同类的 active_model_serializers

转载 作者:太空宇宙 更新时间:2023-11-03 16:03:32 24 4
gpt4 key购买 nike

FeedController 返回一个数组,其中包含以下类的对象:Product、Kit 和 Article。

是否有可能以及如何使用 active_model_serializers 为产品应用 ProductSerializer,为套件应用 KitSerializer,为文章应用 ArticleSerializer?

这应该呈现如下内容:

[
{ "type": "product", other fiels of Product },
{ "type": "kit", other fiels of Kit },
{ "type": "article", other fiels of Article }
]

最佳答案

这应该适用于 0.9.0 版0.10.0 版 最终准备就绪时应该可以开箱即用,但在这个答案,建议你不要使用那个版本(master/edge)

class MyArraySerializer < ActiveModel::ArraySerializer

def initialize(object, options={})
options[:each_serializer] = get_serializer_for(object)
super(object, options)
end

private
def get_serializer_for(klass)
serializer_class_name = "#{klass.name}Serializer"
serializer_class = serializer_class_name.safe_constantize

if serializer_class
serializer_class
elsif klass.superclass
get_serializer_for(klass.superclass)
end
end
end

您可以修改 get_serializer_for 方法以更好地满足您的需要。我用它来处理 STI 子类,其中我的父类定义了所有属性。但是,您需要为每个单独的对象使用单独的序列化程序,因为属性很可能会有所不同。

然后在你的 Controller 中:

render json: @my_array_of_mixed_classes, serializer: MyArraySerializer

关于ruby-on-rails - 数组中不同类的 active_model_serializers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19322311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com