Search code examples
javascriptember.jsember-dataember-cli

Ember Data Get Record From Store First Rather than API with param


I am attempting to load some data based on a slug rather than an id from the route in an ember cli app. I have created a route, the slug param is being correctly passed to the model hook, and I already have the record data in the store since some data gets bootstrapped into the application when it is initialized. However the store is always looking at the api route and not just getting the local version. How can I prevent this?

router.js

this.resource('vendor', {path: '/:slug'}, function () {
      this.resource('category', {path: '/:vendor_id/categories/:category_id'});
      this.resource('product', {path: '/:vendor_id/products/:product_id'});
    });

routes/vendor.js

export default Ember.Route.extend({
    model: function(params) {
        return this.store.query('vendor', {slug: params.slug});
    }
});

and then in the console I can see the api call get fired to

http://localhost:4200/api/vendors?slug={slug from params} 404 (Not Found)

I do plan on building out this endpoint but I am curious as to why it is looking at the API when I can see the data in the ember store.


Solution

  • You are looking for store.filter, without the query parameter which would trigger a network call.

    export default Ember.Route.extend({
        model: function(params) {
            return this.store.filter('vendor', function(vendor) {
                return vendor.get('slug') === params.slug;
            });
        }
    });
    

    By the way, this will keep the model updated with new records matching the filter however they might get added to the store.