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:
- Before saving new patient I'm pushing array of
Medicine
objects tonewPatient.meds
. - Then I save
newPatient
. After save is done I'm going through array of
Medicine
objects pushingnewPatient
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.
- Saved patient doesn't have any meds. In
POST
request to servermeds
is empty array. - Saved meds each has patient id in
patients
. But it always hasnull
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'.