在我工作的地方,我将API代码更新为FastJson (https://github.com/Netflix/fast_jsonapi)。“旧”代码使用的是ActiveModel,并且有ActiveModel::Serializer::CollectionSerializer.new
。我不知道如何将这段代码“翻译”成FastJson接口。
我已经在FastJson文档中搜索过关于集合序列化(https://github.com/Netflix/fast_jsonapi#collection-serialization)的内容,但是我不理解这个例子。
class API::Messages::MessagesSerializer < ActiveModel::Serializer
attributes :id, :name, :description
attribute :chats do
ActiveModel::Serializer::CollectionSerializer.new(
object.user_chats, serializer: API:Messages::ChatUserSerializer
)
end
end
发布于 2019-11-04 20:36:59
当集合被传递到序列化程序中时,它将完美地处理该集合,不需要配置任何额外的东西。以下是序列化程序
class API::Messages::MessagesSerializer
include FastJsonapi::ObjectSerializer
attributes :id, :name, :description
attributes :chats do |message|
API::Messages::ChatsSerializer.new(message. user_chats)
end
end
class API::Messages::ChatsSerializer
include FastJsonapi::ObjectSerializer
attributes ... # add attribute/logic as you want for single chat object
end
你的控制器应该是这样的
def show
render json: API::Messages::MessagesSerializer.new(@message).serialized_json, status: :ok
end
https://stackoverflow.com/questions/58693246
复制相似问题