jasongonzales
jasongonzales

Reputation: 1597

Emberjs, ember-data, localstorage adapter, destroyRecord and all hasMany relations

I am using the localstorage adapter and emnber-data and when I destroy a record, that has a hasMany relation, I want to also destroy all of those.

Here are the models:

App.Category = DS.Model.extend({
  title: DS.attr('string'),
  items: DS.hasMany('item')
});

App.Item = DS.Model.extend({
  name: DS.attr('string'),
  category: DS.belongsTo('category')
});

I have an action called 'destroyCategory' in which I've tried several things but, no matter what I try I only get weirdness.

I've tried looping over the "children", I've tried just destroying the "parent," but none works as expected. I assume I am just missing something basic, so appreciate the help.

EDIT:

OK, I've tried this:

deleteItem: function(user_cat) {
 this.store.find('category', user_cat.id).then(function(category) {
   items = category.get('items');
   items.forEach(function(item, index, enumerable) {
     item.destroyRecord();
   });
   category.destroyRecord();
 });

And the weirdness I get is that it destroys all but one "child" record... Wat?

LAST UPDATE:

This works, but I wonder if there is a better, more idiomatic approach:

deleteItem: function(selection) {
 this.store.find('category', selection.id).then(function(category) {
   items = category.get('items');
   items.toArray().forEach(function(item, index, enumerable) {
     item.destroyRecord();
   });
   category.destroyRecord();
 });
}

Upvotes: 2

Views: 177

Answers (1)

Tom Doe
Tom Doe

Reputation: 906

You can invoke( 'destroyRecord' ) on the items:

deleteItem: function(selection) {
 this.store.find('category', selection.id).then(category => {
   let items = category.get( 'items' );
   items.toArray().invoke( 'destroyRecord' );
   category.destroyRecord();
 });
}

Upvotes: 1

Related Questions