How do you properly handle caching in the store?

I have the following code:

Muskoka.GalleryRoute = Ember.Route.extend({
    model: function() {
        return this.store.find("photo");
    }
});

Now I only want to call the database the first time the user goes to the Gallery route but the above calls the database every time.

How do I call the database only the FIRST time?

I’m aware the this.store.all() references the store cache but I need to go to the database at least once.

3 Likes

Add a controller and load the data from there with store.all(). Don´t delete the route.

The models found by the first call stay cached in Ember Data’s store. Subsequent calls simply serve to refresh the data in the models already in the store, and to pull down models which have appeared server-side since the last lookup was made.

If you want to prevent the “refresh lookup” you can simply wrap the store.find call in an if-statement with a flag stored on the route:

model: function () {
    if (this.get("hasLoadedPhotos"))
    {
        return this.store.all("photo");
    }
    else
    {
        this.set("hasLoadedPhotos", true);
        return this.store.find("photo");
    }
}

The store.all call returns all of the models of the specified type already cached in the store, without performing a server lookup.