How To: CRUD with Validation in Ember.js Using ember-easyForm, ember-validations, and Boostrap

Step 4. Delete Product from Products Index

The easiest feature to implement is to delete a product, as there are no additional templates, routes or controllers required. Let us do that now.

We have already set up the delete buttons next to each product in the /products page. All we have to do is to hook them up to a delete action that performs the deletion. We will insert the delete action in the parent route ProductsRoute, since the action will be used by other routes within the Products section. Here we are taking advantage of the bubbling mechanism in Ember.js to reuse code.

The delete action will take the product to be deleted as a parameter. It will then call the product’s destroyRecord() method, which will delete the record and commit the deletion immediately (for example, by saving it to a database). You may also use the deleteRecord() method which will delete the record but not save the deletion immediately. Finally, the action will redirect the user to /products.

Modify ProductsRoute in app.js so that it looks like this:

App.ProductsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('product');
  },

  actions: {
    // Delete specified product.
    delete: function(product) {
      product.destroyRecord();
      this.transitionTo('products');
    }
  }
});

Let us test that this works. We create a new test that will delete one product, ensure that both the number of products displayed in /products and the number of items in App.Product.FIXTURES decrease by one.

Append to tests.js:

test('delete button works', function() {
  expect(4);
  var productID = 1;

  visit('/products').then(function() {
    var productCount = find('table#products_table tbody tr').length;
    equal(productCount, App.Product.FIXTURES.length);
    click('#product' + productID + ' .delete-button').then(function() {
      var newproductCount = find('table#products_table tbody tr').length;
      equal(App.Product.FIXTURES.length, productCount - 1);
      equal(newproductCount, productCount - 1);
      equal(find('#product' + productID).length, 0);
    });
  });
});

You can get the code for this step by running:

git checkout step-4
Advertisements

5 thoughts on “How To: CRUD with Validation in Ember.js Using ember-easyForm, ember-validations, and Boostrap

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s