Skip to content

Differences to the rails 3 default json response structure

fabrik42 edited this page Apr 26, 2011 · 8 revisions

Differences to the Rails 3 default JSON response structure

Short explanation

To enable JSON responses like this (which adds a single root node to every model rendered in the collection):

{ users: [ { user: { name: "Luke" } },  { user: { name: "Leia" } } ] }

Just add this statement somewhere in your initializers folder, e.g. in config/initializers/acts_as_api.rb

ActsAsApi::Config.include_root_in_json_collections = true

That's it. :)

Longer explanation

While rails wraps a every item in a collection of models in a root node by default acts_as_api doesn't do that:

Rails 3 default

{ users: [ { user: { name: "Luke" } },  { user: { name: "Leia" } } ] }

acts_as_api default

{ users: [ { name: "Luke" }, { name: "Leia" } ] }

Why?

I've chosen another default response format, as the Rails 3 default response format is imho inconsistent, when it comes to render sub resources/associations.

Because Rails 3 doesn't do include the root node for collections of included associations, e.g.

[
    {
        user: {
            created_at: "2011-04-26T08: 43: 10Z",
            updated_at: "2011-04-26T08: 43: 10Z",
            id: 1,
            tasks: [
                {
                    created_at: "2011-04-26T08: 44: 22Z",
                    completed: false,
                    updated_at: "2011-04-26T08: 44: 22Z",
                    id: 2,
                    user_id: 1,
                    description: "Be a Jedi"
                },
                {
                    created_at: "2011-04-26T08: 44: 30Z",
                    completed: false,
                    updated_at: "2011-04-26T08: 44: 30Z",
                    id: 3,
                    user_id: 1,
                    description: "Destroy Deathstar"
                }
                ...
            ],
            last_name: "Skywalker",
            first_name: "Luke"
        }
    },
    ...
]

The items of the tasks sub-collection don't have a wrapping root node each, but the users have.

I don't like this as I find it a little bit confusing, so I decided to leave out all root nodes within a collection. :)