Change relationship during runtime


#1

Hi

I stumbled across a problem with relationships and I don’t know who to solve it the best way.

Example: Lets assume we have a cable with some properties like length, insulation and a type. The type can be “round wire” or “rectangular wire” where each type has different properties. The roundWire has diameter and the rectangular wire has height and width as properties.

Cable = DS.Model.extend({
             length: DS.attr('number'),
         insulation: DS.attr('string'),
          roundWire: DS.belongsTo('roundWire'),
    rectangularWire: DS.belongsTo('rectangularWire')
});

RoundWire = DS.Model.extend({
    diameter: DS.attr('number')
});

RectangularWire = DS.Model.extend({
    height: DS.attr('number'),
    width: DS.attr('number')
});

(in my real world project I have much more types with more individual properties)

In the example above either roundWire or rectangularWire can be set to a value and the other needs to be null. It is never possible that both are set at the same time. My concern is that I have to check which relationship is used and return the corresponding properties. I would like to have instead only one property like:

wire: DS.belongsTo('roundWire' or 'rectangularWire')

I’m quite sure that I’m not the first with such a problem. Are there any best practices to design this desired structure?

Thanks in advance…


#2

What you are looking for is polymorphic relationship. Search the web for examples, but I don’t believe the feature is documented.


#3

Thanks @lightblade. Polymorphic is the keyword to search for. There is at least one “newer” Ember Data example with polymorphic relationships: https://www.toptal.com/emberjs/a-thorough-guide-to-ember-data

Unfortunately the feature is not documented and I would have to change the api response. I think I will stick with documented features and solve it as shown in my example.