Search code examples
ember.jsember-data

Ember hasMany relationship save on create


I'm trying to create an ember data record with a hasMany relationship from a POJO, and it's been remarkably difficult. This is using ember-concurrency (hence the task and yield syntax.

  saveEntry: task(function* (obj){
      let entry = yield this.model.get('entries').createRecord({
        groupId: obj.objectID,
        name: obj.name,
        ...

      }).save();
      obj.owner_ids.forEach((user_id) => {
        this.store.findRecord('user', user_id).then((user) => {
          entry.get('owners').pushObject(user);
          entry.save();
        });
      })
   }).drop();

So the tough bits are the 'obj.owner_ids', which is an array of user_ids. I add each to the array, but then need to save after every pushObject or it doesn't work. And even when it does work, it is throwing a bunch of network errors (probably due to race conditions on the save). There must be a better way, but I haven't found it.


Solution

  • I'm not sure what this.model represents in your code, but you could try fetching all of the users you need and then attaching them at the time you create and save like:

    import { all } from 'rsvp';
    
    saveEntry: task(function* (obj){
      let users = obj.owner_ids.map(userId => this.store.findRecord('user', user_id));
    
      let promises = this.model.get('entries').createRecord({
        groupId: obj.objectID,
        name: obj.name,
        owners: users,
        ...
      }).save()
    
      // all() waits for an an array of promises to return
      yield all(promises);
    }).drop();