如何在FastJson API中使用CollectionSerializer?

我将工作所在的API代码更新为FastJson(https://github.com/Netflix/fast_jsonapi)。 “旧”代码正在使用activeModel并具有 activeModel::Serializer::CollectionSerializer.new。我不知道如何将该代码“转换”为FastJson API。

我已经在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 

lulujiaojiao 回答:如何在FastJson API中使用CollectionSerializer?

当集合将在序列化器中传递时,它将完全无需额外配置即可处理该集合。以下是序列化器

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://www.f2er.com/3166841.html

大家都在问