Search code examples
ember.jsfiltermodelstore

Filtering ember model in router


I'm trying to return the model store into my template but before I do the return I would like to filter by a certain property, returning only those records that have that property. Also, in my model, I'm overriding the default 'id' with a serializer.

In my console I'm getting a "store is not defined ReferenceError: store is not defined" Any ideas ?

Here's my route:

import Ember from 'ember';
import DS from 'ember-data';

export default Ember.Route.extend({

    model: function() {

    return this.store.find('link').then(function(links) {
        return store.filter('link', { linkTypeCode: 'NSL' });

    });

    }

});

Model:

import DS from 'ember-data';

export default DS.Model.extend({
    artifactId : DS.attr('number'),
    artifactName : DS.attr('string'),
    linkTypeCode : DS.attr('string')
});

Solution

  • Your route is calling store instead of this.store. Since this is within an asynchronous callback, this.store will also need to have been cached to a variable.

    Additionally, once you fix this you will encounter an error with your filter. The filter expects a function.

    import Ember from 'ember';
    import DS from 'ember-data';
    
    export default Ember.Route.extend({
    
      model: function() {
        var Store = this.store;
    
        return Store.find('link').then(function(links) {
          return Store.filter('link', function (record) { 
            return record.get('linkTypeCode') === 'NSL'; 
          });
        });
      }
    
    });
    

    I would also note that DS.filter returns a live record array, meaning it's records are always kept up-to-date with the records the store learns about. It would be possible to do the following.

    Store.find('link');
    return Store.filter('link', function (record) {
      return record.get('linkTypeCode') === 'NSL';
    });