Skip to content

Serialize collection of polymorphic objects #121

@cazacutudor

Description

@cazacutudor

Problem

I want to serialize a collection that's containing polymorphic objects, how can i do that ? It is supported ?

Example

MediaSerializer.rb

class MediaSerializer
      include JSONAPI::Serializer
end

MovieSerializer.rb

class MovieSerializer
      include JSONAPI::Serializer

      attributes :name
end

ShowSerializer.rb

class ShowSerializer
      include JSONAPI::Serializer

      attributes :name
end

LiveShowSerializer.rb

class LiveShowSerializer
      include JSONAPI::Serializer

      attributes :name
end

controller.rb

data = [
    <Api::Entities::Movie id=10 name="Zoro" position=1>, 
    <Api::Entities::Show id=20 name="Zoro si Precini" position=2>,
    <Api::Entities::LiveShow id=30 name="Zoro si Dus-manii" position=3>
]

MediaSerializer.new(data).serializable_hash.to_json

# expected output
"data": [
#   {
#     "id": "1",
#     "type": "movie",
#     "attributes": {
#       "name": "Zoro",
#     }
#   },
#   {
#       "id": "2",
#       "type": "show",
#       "attributes": {
#         "name": "Zoro si Precini",
#       }
#   },
#   {
#     "id": "3",
#     "type": "live_show",
#     "attributes": {
#       "name": "Zoro si Dus-manii",
#     }
#   }
# ]

Specifications

  • Version: 2.1.0
  • Ruby version: 2.6.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions