Format for Embedded Polymorphic Associations


#1

I’m using Rail’s ActiveModelSerializer to serialize most of my data. The only exception is polymorphic relationships, which ActiveModelSerializer doesn’t yet support. So that means I’ve got to find a way to embed those relationships by hand.

In my use case, async: true won’t really work. So embedding is necessary. My question is, what would the format for embedded polymorphic relationships be like. If you only wanted to embed a reference to a polymorphic model, it’d look something like this:

{
  "membership": {
    "member": 1,
    "memberType": "User"
  }
}

So should embedding it look something like this?

{
  "membership": {
    "member": { "id": 1, "memberType": "User", "name": "Joe" }
  }
}

#2

Assuming a “Membership” that hasMany “Member” instances where “Member” is a base class with the attribute “color” and subclasses “User” with attributes “firstName” and “lastName” and “Group” with the attribute “name”:

membership.js

export default DS.Model.extend({
  members: DS.hasMany('member', {polymorphic: true})
});

member.js

export default DS.Model.extend({
  color: DS.attr('string')
});

group.js


export default Member.extend({
  name: DS.attr('string')
});

user.js

import Member from 'app/models/member';

export default Member.extend({
  firstName: DS.attr('string'),
  lastName: DS.attr('string')
});

Sample JSON

{
  "memberships": [
    {
      "id": "1",
      "members": [
        {
          "id": "10",
          "type": "user"
        },
        {
          "id": "15",
          "type": "group"
        }
      ],
    }
  ],
  "users": [
    {
      "id": "10",
      "color": "green",
      "first_name": "Ronald",
      "last_name": "Spork"
    }
  ],
  "groups": [
    {
      "id": "15",
      "color": "red",
      "name": "Administrators"
    }
  ]
}

#3

Thanks for the fast reply @jdanielpowell! This is exactly what I needed.

Out of curiousity, what is the export default and import syntax you’re using? It’s way more concise than what I’m used to.


#4

export and import are syntax for ECMAScript 6 modules. See https://github.com/stefanpenner/ember-app-kit for example usage.