Search code examples
ember.jsember-data

Refreshing a parent route's model when creating new record in a child route?


I have a parent route that lists a number of objects and a child route that allows users to create new objects in a modal dialog. Something like:

// Parent route (app.colours)
export default Ember.Route.extend({
    model() {
        return this.store.findAll('colour');
    },
}

and a child route that allows you to add new objects:

// Child route (app.colours.create)
export default Route.extend({
    model() {
        return this.store.createRecord('colour');
    },
    actions: {
        save(colour) {
            color.save().then(() => this.transitionTo('app.colours'));
        }
    }

I notice that when I successfully create a new colour record and transition back to the parent route, the new record isn't in the list as the parent route's model hasn't been refreshed.

How can I tell the parent route to refresh its model from the child route?


Solution

  • Actions to the rescue. I got it working by sending the parent an action:

    // Parent route (app.colours)
    export default Ember.Route.extend({
        model() {
            return this.store.findAll('colour');
        },
        actions: {
            refreshModel() {
                this.refresh();
            }
        }
    }
    

    and

    // Child route (app.colours.create)
    export default Route.extend({
        model() {
            return this.store.createRecord('colour');
        },
        actions: {
            save(colour) {
                color
                    .save()
                    .then(() => {
                        this.send('refreshModel');
                        this.transitionTo('app.colours'));
                    }
            }
        }
    }