Ember Data: delete child record from parent view

I have association as Offer has many items

On offer-show page, am displaying the details of all items that belongs to offer

Along with each item, am adding show link and destroy button.

Facing issue while implementing destroy of item

view: (offer-page)

    {{#each items}}
      <tr>
        <td><img {{bind-attr src=defaultImage }}></td>
        <td>{{this._data.name}}</td>
        <td>{{#link-to 'item' this}}Show{{/link-to}}</td>
        <td><button {{action 'removeItem' this.id}}>Remove</button></td>
      </tr>
    {{/each}}

offer controller:

import Ember from 'ember';
export default Ember.ObjectController.extend({
  needs: ['item'],

  actions: {
    removeItem: function(item) {
      //...what should i add here
    }
  }
});

item controller

import Ember from 'ember';
export default Ember.ObjectController.extend({
  actions: {
    remove: function() {
      var currentItem = this.get('model');
      var offer = currentItem.get('offerId');
      currentItem.destroyRecord().then(function() {
        router.transitionTo('offer', offer);
      });
    }
  }
});

routes

this.resource('offer', { path: '/:offer_id'}, function() {
  this.route('index', { path: '/'});
  this.resource('items', function(){
    this.resource('item', { path: ':item_id'}, function() {
      this.route('remove');
    });
  });

can anyone pls help me…how i can achieve it?

How exactly is the items property defined on the offer controller? Supposing it is simply an array, rather than a computed property…

If you would like to remain on the offer route while removing items via the “Remove” buttons in the items list, then you could define the removeItem action like so:

actions: {
	removeItem: function(item) {
		this.get('items').removeObject(item);
		item.destroyRecord();
	}
}

And to facilitate this method, modify your template to raise this to the removeItem handler:

{{#each items}}
	<tr>
		<td><img {{bind-attr src=defaultImage }}></td>
		<td>{{this._data.name}}</td>
		<td>{{#link-to 'item' this}}Show{{/link-to}}</td>
		<td><button {{action 'removeItem' this}}>Remove</button></td>
	</tr>
{{/each}}

The {{each}} helper will notice when an item has been removed, and it will disappear from the list.

1 Like

@macu Thank you so much…!! It works perfectly… :smile: Nicely explained…