Ember Data: Polymorphic Associations

Created by Luke Galea / @lukegalea

What are polymorphic associations?


"A relationship from one class to multiple classes."

Person = DS.Model.extend({
  name: attr('string'),
  neckbeard: true
});
            

Person = DS.Model.extend({
  name: attr('string'),
  neckbeard: true,
  pets: hasMany('pet', { polymorphic: true })
});
            

Person = DS.Model.extend({
  name: attr('string'),
  neckbeard: true,
  pets: hasMany('pet', { polymorphic: true })
});

Pet = DS.Model.extend({
  owner: belongsTo('person')
});

Cat = Pet.extend({
  lives: attr('number', {defaultValue: 9})
});
          

App.Person = DS.Model.extend({
  name: attr('string'),
  neckbeard: true,
  pets: hasMany('pet', { polymorphic: true })
});

Pet = DS.Model.extend({
  owner: belongsTo('person')
});

Cat = Pet.extend({
  lives: attr('number', {defaultValue: 9})
});

Dog = Pet.extend({
  fleas: attr('number', {defaultValue: 0})
});
          

App.Person = DS.Model.extend({
  name: attr('string'),
  neckbeard: true,
  pets: hasMany('pet', { polymorphic: true })
});

Pet = DS.Model.extend({
  owner: belongsTo('person')
});

Cat = Pet.extend({
  lives: attr('number', {defaultValue: 9})
});

Dog = Pet.extend({
  fleas: attr('number', {defaultValue: 0})
});

HoneyBadger = Pet.extend({
  viciousness: attr('number', {defaultValue: 0})
});
          

DEMO

Different adapters per type

API can serve references to other APIs