How to save models with many-to-many relationship

2019-05-18 09:41发布

I'm stuck with this problem for so long that I think that I'm missing something obvious. Here's simplified model of my case:

There is Patient that has all meds that he/she takes. And there is Medicine that has all patients who takes it.

// Patient model
Yo.Patient = DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    meds: DS.hasMany('medicine')
});
// Medicine model
Yo.Medicine = DS.Model.extend({
    title: DS.attr('string'),
    patients: DS.hasMany('patient')
});

I've read official manual and many resources. The last one and closest to my case was this Toptal tutorial. Here's what I do now:

  1. Before saving new patient I'm pushing array of Medicine objects to newPatient.meds.
  2. Then I save newPatient.
  3. After save is done I'm going through array of Medicine objects pushing newPatient to each of them and saving each.

    newPatient.get('meds').pushObjects(meds);
    newPatient.save().then(function (p) {
        for (var i = 0; i < meds.length; i++) {
            meds[i].get('patients').pushObject(p);
            meds[i].save();
        };
    });
    

But result isn't what it meant to be.

  1. Saved patient doesn't have any meds. In POST request to server meds is empty array.
  2. Saved meds each has patient id in patients. But it always has null on zero position of array.

Also there already was similar question on StackOverflow. But solution is not very usable. And answer is 1.5 years old which is eternity in Ember world.

Edit Proposed in comments by Josh RecordArray as I see now cant't be used in my case. Or maybe it can, but I don't know how. I have a form for creating new patient. There's list of meds checkboxes. So I need to push only checked ones to newPatient.meds.

What I do now: I get ids of checked checkboxes (which equals to corresponding object id), then get Medicine instance for each id and put it in array. Then I try to push it in `newPatient.meds'.

1条回答
Root(大扎)
2楼-- · 2019-05-18 10:16

You should use serializer for this issue. Here is answer to your question

查看更多
登录 后发表回答