bfcoder
bfcoder

Reputation: 3132

Ember create a polymorphic record

I am trying to create a record for a model that has a polymorphic relationship.

Here is the model:

App.SupportedTransportationMethod = DS.Model.extend({
  resource: DS.belongsTo('resource', { polymorphic: true }),
  transportationMethod: DS.belongsTo('transportationMethod')
});

And the model I'm trying to create the record with:

App.Contact = DS.Model.extend({
  supportedTransportationMethods: DS.hasMany('supportedTransportationMethod', { async: true }),
  companyName: DS.attr('string')
});

And here I am trying to create a record:

supportedTransportationMethod = this.store.createRecord('supportedTransportationMethod', {
  transportationMethod: transportationMethod,
  resource: contact
});

But I get an assertion error:

Uncaught Error: Assertion Failed: You can only add a 'resource' record to this relationship 

I have a jsbin showing this. If you click one of the checkboxes then you'll get the error. I am trying to create the record down in the CheckboxItemController.

http://jsbin.com/qebis/6/

Any ideas how I am to accomplish this? I looked at this SO but that doesn't fly well with dynamically creating where you have no idea what the id will be. Nor does pushing feel right.

UPDATE:

If I use the ember-data prod version, it allows the creation (because the assertion is code is removed from the prod version). So I'm wondering if this is a bug in the assertion code?

Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeClass);

It does however create it with the type set to the current model type even if it is extending from a base model. Not sure yet if that is a good thing or not...

UPDATE 2:

Here is another jsbin to show the effects of the previous update. http://jsbin.com/qebis/7/edit

Upvotes: 1

Views: 717

Answers (2)

aceofspades
aceofspades

Reputation: 7586

For those using ember-cli, note that that MODEL_FACTORY_INJECTIONS = true prevents model inheritance form working for polymorphic relationships as of Ember Data : 1.0.0-beta.11.

See https://github.com/emberjs/data/issues/2065

Upvotes: 4

Cyril Fluck
Cyril Fluck

Reputation: 1581

Ember Data expects the records to be inherited from the same base class. In your case you're specifying resource but it doesn't seem like you have defined it as a DS.Model.

You should have something like:

App.Resource = DS.Model.extend();

App.Contact = App.Resource.extend({
  supportedTransportationMethods: DS.hasMany('supportedTransportationMethod', { async: true }),
  companyName: DS.attr('string')
});

Upvotes: 2

Related Questions