N
N
Nikita2014-09-24 03:17:52
JavaScript
Nikita, 2014-09-24 03:17:52

How to store objects with many-to-many relationship in Ember.js?

I have been struggling with the problem for a long time, because I suspect that the solution is elementary. Reduced to an abstract simplified model. Suppose there is a patient and complaints

// Модель пациента
Yo.Patient = DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    zhalobs: DS.hasMany('zhaloba')
});
// Модель жалобы
Yo.Zhaloba = DS.Model.extend({
    title: DS.attr('string'),
    patients: DS.hasMany('patient')
});

All complaints must be recorded in the patient, all patients in the complaint.
I try to insert pushObjects with an array of complaint objects before saving the patient, then I save the patient. After that, I run through the array of complaints and each one I do a pushObject with a new patient.
newPatient.get('zhalobs').pushObjects(zs);
newPatient.save().then(function (p) {
    for (var i = 0; i < zhalobs.length; i++) {
        zhalobs[i].get('patients').pushObject(p);
        zhalobs[i].save();
    };
});

But in the end, I don't get what I need.
1. The patient does not have any complaints. Moreover, in the POST request, the zhalobs field is an empty array. So the problem is not with the server.
2. A patient is added to the complaints, but null is always set to the null element of the array .
I communicate with Ember quite recently, maybe I didn’t understand his logic of actions correctly. I would be grateful for advice.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Romanov, 2014-10-26
@Kaer_Morchen

I ran into a similar problem, I don't remember how I solved it, it seems like this:

DS.JSONSerializer.reopen({
    serializeHasMany : function(record, json, relationship) {
        var key = relationship.key;

        var relationshipType = DS.RelationshipChange.determineRelationshipType(
            record.constructor, relationship);

        if (relationshipType === 'manyToNone'
            || relationshipType === 'manyToMany'
            || relationshipType === 'manyToOne') {
            json[key] = Ember.get(record, key).mapBy('id');
            //TODO support for polymorphic manyToNone and manyToMany relationships
        }
    }
});

I advise you to update ember-data to the latest version (currently 1.0.0-beta.11)
In your case, it is better to use EXPLICIT INVERSES
Very useful article on relationships between models.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question