mercredi 5 juillet 2017

How do I serialize a has-many-through relationship with Ember's JSONAPIAdapter?

I have three models: User, Group, and Membership. A User has many Groups through Memberships. I have a form to invite a new user and assign them to zero or more groups all at once.

What I Want

The JSON I expect to send to the server for POST /users looks like

{
  data: {
    type: 'user',
    attributes: { name: 'Sam Sample' }
  },
  relationships: {
    memberships: {
      data: [
        {
          type: 'membership',
          relationships: {
            group: {
              data: {
                type: 'group',
                id: 12345
              }
            }
          }
        },
        {
          type: 'membership',
          relationships: {
            group: {
              data: {
                type: 'group',
                id: 67890
              }
            }
          }
        }
      ]
    }
  }
}

What I Tried

I tried adding serialize: true to the relevant serializers:

// serializer:user
import ApplicationSerializer from './application';
export default ApplicationSerializer.extend({
  attrs: {
    memberships: { serialize: true }
  }
})

// serializer:membership
import ApplicationSerializer from './application';
export default ApplicationSerializer.extend({
  attrs: {
    group: { serialize: true }
  }
})

That gets me some of the JSON I expect, but not all of it. Specifically, I get the membership objects, but not the groups within them

{
  data: {
    type: 'user',
    attributes: { name: 'Sam Sample' }
  },
  relationships: {
    memberships: {
      data: [
        {
          type: 'membership'
        },
        {
          type: 'membership'
        }
      ]
    }
  }
}




Aucun commentaire:

Enregistrer un commentaire