rails-api/active_model_serializers — pull request #423 by polmiro (2013-10-25 23:39:36+00:00)
Title: Add support polymorphic associations

Following up with https://github.com/rails-api/active_model_serializers/pull/367 and https://github.com/rails-api/active_model_serializers/pull/376 I added support for the polymorphic has_one and has_many associations starting out from the current master branch.

Here there is a few different ways we can choose from when serializing the polymorphic models. I choose the one one that looks best but I am open to changes.

## Embedding Polymorphic Associations

Because we need both the id and the type to be able to identify a polymorphic associated model, polymorphic associations are serialized in a slightly different format than common ones.

When embedding entire objects:

```ruby
class PostSerializer < ActiveModel::Serializer
attributes :id, :title
has_many :attachments, polymorphic: true
end
```

```json
{
"post": {
"id": 1,
"title": "New post",
"attachments": [
{
"type": "image"
"image": {
"id": 3
"name": "logo"
"url": "http://images.com/logo.jpg"
}
},
{
"type": "video"
"video": {
"id": 12
"uid": "XCSSMDFWW"
"source": "youtube"
}
}
]
}
}
```

When embedding ids:

```ruby
class PostSerializer < ActiveModel::Serializer
embed :ids

attributes :id, :title
has_many :attachments, polymorphic: true
end
```

```json
{
"post": {
"id": 1,
"title": "New post",
"attachment_ids": [
{
"type": "image"
"id": 12
},
{
"type": "video"
"id": 3
}
]
}
}
```