StickByAtlas
StickByAtlas

Reputation: 357

Ember Data: resolve ambiguous inverses when using multiple belongsTo relationships between two models

Say I have two Ember Data models: competition and participant

My competition model stores the following data: date, first, second and third. The first, second and third properties will all store IDs of the unique competitors who came in first, second and third place.

My participant model stores the following data: name, surname and competition

Participants only compete in one competition, so the participant model doesn't need a hasMany relationship on competition.

How do I model this in Ember Data?

Here's what I thought might work:

// app/models/competition.js

export default DS.Model.extend({
  rev: DS.attr('string'),
  date: DS.attr('date', {defaultValue: function() { return new Date(); }}),
  first: DS.belongsTo('participant'),
  second: DS.belongsTo('participant'),
  third: DS.belongsTo('participant')
});

// app/models/participant.js

export default DS.Model.extend({
  rev: DS.attr('string'),
  name: DS.attr('string'),
  surname: DS.attr('string'),
  competition: DS.belongsTo('competition')
});

The problem is that the competition key on participant.js requires an explicit inverse, and there's no way of knowing which of the three keys on competition it may relate to.

How should I be specifying my inverses? Do both the competition and participant models require explicit inverses? If so, what should they be? Is this kind of data structure even possible in Ember Data? Should I use a different approach altogether?

Please weigh in. I've turned this problem around in my head for hours, and none of my workarounds have succeeded.

Upvotes: 1

Views: 213

Answers (1)

brg
brg

Reputation: 3953

I haven't used ember-data polymorphic association myself, but I believe a polymorphic belongsTo association might suit your needs. My answer is adapted from this blog post . Also check this two tutorials: http://www.toptal.com/emberjs/a-thorough-guide-to-ember-data and http://blog.unspace.ca/post/107228551852/luke-galea-on-ember-data-polymorphic-associations

 //app/models/competition.js
 export default DS.Model.extend({
   rev: DS.attr('string'),
   date: DS.attr('date', {defaultValue: function() { return new Date(); }}),
   participant: DS.belongsTo("particpant", {polymorphic: true,   async: true})
  });

 // app/models/participant.js
 export default DS.Model.extend({
   rev: DS.attr('string'),
   name: DS.attr('string'),
   surname: DS.attr('string'),
   competition: DS.belongsTo('competition')
 });

 // app/models/first.js
 import Participant from '../participant';
 export default Participant.extend({
 });

 // app/models/second.js
 import Participant from '../participant';
 export default Participant.extend({
 });

Upvotes: 0

Related Questions