Should records be filtered in the route or the controller?


#1

I’m going through the Ember.js course at Code School and Gregg Pollack first used the filter method in a controller, explaining that the controller is used to decorate the model. But then in the next section he filtered records in the Route, chaining the method on to ‘store.findAll’.

I’m relatively new to Ember so this is confusing. In the first instance, we have an array of products that we want to filter though to retrieve an array of onSale products to post in the index template. We retrieved the model on the Index Route:

App.IndexRoute = Ember.Route.extend({
    model: function() {
	return this.store.findAll('product');
    }
});

Then the Route sends the products to the controller where we can decorate the data and reduce it to only 3 products.

App.IndexController = Ember.ArrayController.extend({
  onSale: function() {
	return this.filterBy('isOnSale').slice(0, 3);
  }.property('@each.isOnSale')
});

I understand this much. But then we create a link to the ‘products/onsale’ template that will list out all onsale products. We create a ProductsOnsaleRoute where we use modelFor to pull in the parent model but then we go ahead and filter in the Route rather than creating a ProductsOnsaleController and filtering there. Is there an explanation for this?

App.ProductsOnsaleRoute = Ember.Route.extend({
  model: function() {
    return this.modelFor('products').filterBy('isOnSale');
  }
});

#2

I guess it depends on the use case, if the controller ever needs to know about items not on sale then it would make sense to have a computed on the controller. Otherwise, I would put it on the router within the model hook.