Andrew Fan
Andrew Fan

Reputation: 87

How to commit related models

I'm working with ember-pre4 and ember-data rev 11.

Models:

A = DS.Model.extend({
    //some other fields
    b: DS.hasMany('B')
})
B = DS.Model.extend({
    //some other fields
    a: DS.hasOne('A') 
})

In my router I create an instance of model A and create an instance of model B and connect them. They both don't have server-side id. Something like this:

var a = A.createRecord();
    b = B.createRecord();
b.set('a', a)
a.get('b').addObject(b)

When I want to save those models I make:

a.transaction.commit()

And I expected to see:

  1. Save a with empty b // []
  2. After saving a pass a's id into b and save b
  3. After saving b refetch a

But unfortunately ember does 2 request in parallel and a's request data is:

"{//some fields, b: [/url_to_b//]}" // we dont have b's id 

b's request data is:

"{//some fields } // we dont have a's id

What is the best way to solve this problem, does new ember have a default solution for my situation or I should do all stuff manually?

Upvotes: 2

Views: 378

Answers (1)

Andrew Fan
Andrew Fan

Reputation: 87

Solution: I wrapped createRecord function in waitForParents function:

waitForParents:function (record, callback, context) {
    var observers = new Em.Set();

    record.eachRelationship(function (name, meta) {
        var relationship = get(record, name);

        if (meta.kind === 'belongsTo' && relationship && get(relationship, 'isNew')) {
            var observer = function () {
                relationship.removeObserver('id', context, observer);
                observers.remove(name);
                finish();
            };

            relationship.addObserver('id', context, observer);
            observers.add(name);
        }
    });

    finish();

    function finish() {
        if (observers.length === 0) {
            callback.call(context);
        }
    }
},

createRecord:function (store, type, record) {
   this.waitForParents(record, function () {   
   // createRecord code here 
   }
}

Upvotes: 1

Related Questions