How to embed belongsTo relationship in model with custom primaryKeys


#1

Im getting the error Error: Assertion Failed: You need to pass a model name to the store's modelFor method whilst trying to setup a synchronous embedded data relationship on the model.

My API response data has the following structure:

{
  "sites": [
    {
      "site_id": 7382,
      "services": [
        {
          "instance_id": 19118,
          ...
        },
        ...
      }
   ]
}

I have the following model, route and serializer files which define a custom primaryKey:

// models/site.js
const attr = DS.attr;
const hasMany = DS.hasMany;

export default DS.Model.extend({
  // services: attr(), // this picks up the data if active

  services: DS.hasMany('service', { async: false })
});

// models/service.js
const attr = DS.attr;
const belongsTo = DS.belongsTo;

export default DS.Model.extend({
  site: DS.belongsTo('site')
});

// serializers/site.js
export default ApplicationSerializer.extend({
  primaryKey: 'site_id',
  attrs: {
    services: { embedded: 'always' }
  }
});

// serializers/service.js
export default ApplicationSerializer.extend({
  primaryKey: 'instance_id',
  attrs: {
    site: { embedded: 'always' }
  }
});

// routes/sites/index.js
export default Ember.Route.extend({
  model: function() {
    let superQuery = this._super(...arguments),
        org = superQuery.customer_orgCode;
    return this.store.query('site', {org:org});
  }
});

// routes/services/index.js
export default Ember.Route.extend({
  model: function() {
    return this.store.findAll('service');
  }
});

I have a feeling that I need to set a modelFor relationship in the service route, but can’t figure out how to call it on an embedded realtionship.


#2

Hey @ezy! You need to include the EmbeddedRecordsMixin in the serializer to get the embedded belongsTo to work correctly.

So it would look like this:

//serializers/site.js
import DS from 'ember-data';

export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
  primaryKey: 'instance_id',
  attrs: {
    site: { embedded: 'always' }
  }
});

I hope this can help you.


#3

Hey, thanks for the response @josemarluedke. I’ve tried this but keep getting an error: You need to pass a model name to the store's modelFor method.

Pretty sure this is to do with having a custom primaryKey for both site and service which makes Ember Data bork.