jeudi 15 juin 2017

Error while processing route: ... Assertion Failed: You tried to push data with a type ... but no model could be found with that name

I've been having some problem with relationships/includes and serializers using Ember with JSONAPI.

I have a route to show a patient's info:

import Ember from 'ember';

export default Ember.Route.extend({
  model(params){
    return this.store.find('patient', params.patient_id);
  }
});

And I have this two models :

patients :

import DS from 'ember-data';

export default DS.Model.extend(validations, {
  name : DS.attr('string'),
  email : DS.attr('string'),
  gender : DS.attr('string'),
  birthDate : DS.attr('date'),
  description : DS.attr('string'),
  anamnesis : DS.belongsTo('anamnesis')
});

and anamnesis :

import DS from 'ember-data';

export default DS.Model.extend({
  smokes : DS.attr('boolean'),
  drinks : DS.attr('boolean'),
  drugUser : DS.attr('boolean')
});

as you can see, I have a one-to-one relationship between them.

Now, i have this JSONAPI response from my Ruby on Rails backend

{  
  "data":{  
    "id":"3",
    "type":"patients",
    "attributes":{  
        "name":"paciente 3",
        "gender":"female",
        "email":"teste3@teste.com",
        "birth-date":"2017-06-04T02:59:37.435Z"
    },
    "relationships":{  
      "anamnesis":{  
        "data":{  
          "id":"2",
          "type":"anamneses"
        }
      }
    }
  },
  "included":[  
    {  
      "id":"2",
      "type":"anamneses",
      "attributes":{  
        "smokes":null,
        "drinks":null,
        "drug-user":null
      }
    }
  ]
}

When trying to serialize the relationship and included it looks for the anamnese (from the backend's response type anamneses) model instead of anamnesis.

Error while processing route: ... Cannot read property 'type' of null TypeError: Cannot read property 'type' of null

So I had to create a PatientSerializer to fix this problem:

import DS from 'ember-data';
import Ember from 'ember';

export default DS.JSONAPISerializer.extend({
  modelNameFromPayloadKey(payloadKey){
    if(payloadKey === 'anamneses'){
      return 'anamnesis';
    } else {
      return this._super(payloadKey);
    }
  },
  modelNameFromPayloadType(payloadType){
    if(payloadKey === 'anamneses'){
      return 'anamnesis';
    } else {
      return this._super(payloadType);
    }
  },
});

I know it might not be the best solution but I can't even try something else beacuse it now shows me this error:

Error while processing route: ... Assertion Failed: You tried to push data with a type 'anamnese' but no model could be found with that name.

What I am missing? I am fixing it the wrong way?




Aucun commentaire:

Enregistrer un commentaire