Remove index from "hasMany" array?

Hey guys, I’m trying to implement a feature that allows users to remove an index from a Model’s hasMany field. Here’s an example model:

// Model
var Party = DS.Model.extend({
  guests: DS.hasMany('person', { async: true })
});

// Route
actions: {
    remove: function(personId) {
        var party = this.get('party');
        // ???
    }
}

I have a button that triggers the “remove” action, but I can’t figure out how to pull them from the model. I tried converting the model into JSON, manipulating the array, then pushing it back into the store. It feels like I should be able to edit the model directly and save without the user ever knowing.

I’m loving Ember, but there are lots of little stylistic questions like this that are tripping me up from doing things “The Ember Way”.

Thanks for you help.

Can you please clarify what you mean by “remove an index from a Model’s hasMany field” ?

When an instance of the Party model is fetched from the database the guests property will be an array of person models. I’m wondering how I remove an index from the guests attribute and propagate that change to the backend.

I imagine it would be something like this.

// Model
var Party = DS.Model.extend({
  guests: DS.hasMany('person', { async: true })
});

// Route
actions: {
    remove: function(personId) {
        var party  = this.get('controller.model.party');
        var person = this.store.find('person', personId);

        if (party && person) {
          party.get('guests').removeObject(person);
          party.save();
        }
    }
}
1 Like

I assume you mean party.get('guests').removeObject(person);, which did the trick. I wasn’t aware of the MutableEnumerable class and knowing about it answers a lot of other questions I had around Ember Data. Thanks.

It looks like party needs to refetch guests after the save, which causes a noticeable lag in the UI. Is there anything I can do to stop that? Is this where I should set { async: false } in my model?

Yup

So you’re saying it sends a DELETE followed by a GET? I would think it would do a GET when you do the party.get('guests') but would not send a GET again after removeObject since you are simply removing an object.