How to define a nested route to render when hitting the parent in Ember

StackOverflow https://stackoverflow.com/questions/23684593

  •  23-07-2023
  •  | 
  •  

Question

I have a blog route, and a blog-post route.

Router:

App.Router.map(function () {
    this.resource('blog', function () {
        this.route('post', {path: ':id/:title'});
    });
});

Routes:

App.BlogRoute = Ember.Route.extend({
    model: function () {
        return this.store.find('BlogPost');
    }
});

App.BlogPostRoute = Ember.Route.extend({
    model: function (params) {
        return this.store.findById('BlogPost', params.id);
    },
    serialize: function (model, params) {
        return {
            id: model.get('id'),
            title: Ember.String.dasherize(model.get('title'))
        }
    }
});

In my Handlebars template for the parent blog route I have an {{outlet}} that works fine when I click one of the {{#link-to}}s.

What I want to do is render by default the most recent (highest ID) blog post when a user goes to the /blog route.

I found this question and tried this as a result, to no avail:

App.BlogIndexRoute = Ember.Route.extend({
    redirect: function () {
        var latest = 3;
        this.transitionTo('blog.post', {id: latest});
    }
});

(latest is just a placeholder for this.model.pop() or whatever it needs to be.)

I just can't figure out how exactly to load the sub route with the data from the model.

Était-ce utile?

La solution

You can fetch the model for any resource/route that has already been fetched (aka parent resources) using modelFor

App.BlogIndexRoute = Ember.Route.extend({
    redirect: function () {
        var blogs = this.modelFor('blog');
        if(blogs.get('length')){
           this.transitionTo('blog.post', blogs.get('firstObject')); // or blogs.findBy('id', 123)
        }
    }
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top