Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning to a hasMany relationship in Ember Data

I'm trying to get my head around Ember Data models and have an issue trying to assign a collection of objects found using store.findAll() to a hasMany relationship of an ember data model.

I have two models defined:

App.Leaf = DS.Model.extend({
    text: DS.attr('string'),
    branch: DS.belongsTo('App.Branch')
});

App.Branch = DS.Model.extend({
    lotsOfLeaves: DS.hasMany('App.Leaf')
});

If I assign the relationship as part of createRecord()

    App.store.loadMany(App.Leaf,[
        { id: 1, text: "Hello, I'm leaf 1", branch_id: 1 },
        { id: 2, text: "Hello, I'm leaf 2", branch_id: 1 }
    ]);
    var allLeaves = App.store.findAll(App.Leaf);
    var oneBranch = App.Branch.createRecord({ id: 1, lotsOfLeaves: allLeaves });

then it fails (silently) as oneBranch.get('lotsOfLeaves.length') is 0.

Similarly, it fails silently if I assign the relationship after the association:

    var all = App.store.findAll(App.Leaf);
    oneBranch.set('lotsOfLeaves', all);

I understand that I can use pushObject() on oneBranch.get('lotsOfLeaves') to add each leaf individually but is that the only way?

like image 956
EdgifyJP Avatar asked Sep 24 '12 15:09

EdgifyJP


1 Answers

The MutableArray class also defines a pushObjects() method that you ought to be able to use to add all of them at once.

Documentation is here: http://docs.emberjs.com/symbols/Ember.MutableArray.html#method=pushObjects

like image 156
Mike Hickman Avatar answered Nov 06 '22 17:11

Mike Hickman