rails-api/active_model_serializers — pull request #461 by fivetanley (2013-12-02 21:30:22+00:00)
Title: Add embed_namespace and embed_in_root_key options

After talking with @steveklabnik in #jsonapi on Freenode, I decided to give this a go. It could probably use some more work (I'm not totally in love with "embed_namespace" and "embed_in_root_key" names, hoping someone can provide alternatives).

The purpose of this pull request is to allow hooks to produce JSON that is compatible with the (current draft!) of the JSONAPI spec. View "Compound Documents" on this page: http://jsonapi.org/format/#id-based-json-api

`embed_namespace` allows you to embed ids/etc underneath a namespaced
key. For example:

```ruby
class PostSerializer < ActiveModel::Serializer
embed :ids, embed_namespace: :links

attributes :name

has_many :comments
end
```

Gives the following JSON:

```json
{
"post": {
"id": 1,
"name": "Blog",
"links": {
"comments": [ 1, 2, 3 ]
}
}
}
```

`embed_in_root_key` option allows you to sideload resources underneath
a namespace in the document root. For example:

```ruby
class PostSerializer < ActiveModel::Serializer
embed :ids, include: true, embed_in_root_key: :linked

attributes :name

has_many :comments, embed_namespace: :links
end
```

Gives the following JSON:

```json
{
"post": {
"id": 1,
"name": "Blog",
"links": {
"comments": [ 1, 2, 3 ]
}
},
"linked": {
"comments": [ 1, 2, 3 ]
}
}
```

The two combined as in the above example allow for compliance with the
(current) JSONAPI spec for using "linked/links".