Small deviation from the sample blog posts app in the intro video. Please advice

Hi, I am a beginner in Ember. I followed the intro video and created the blog post app. However when the /posts URL is hit or the posts link clicked, I wanted to display the first post on the right (instead of the message like “please select a post”). I achieved it using this PostsRoute configuration.

App.PostsRoute = Ember.Route.extend({
model: function() {		
	return App.Post.find();
},
renderTemplate: function() {
	this.render('posts');
	var firstPost = App.Post.find(1);
	if(firstPost.get('isLoaded')) {
		this.transitionTo('posts.post', firstPost);
	} else {
		firstPost.on('didLoad', this, function () {
    		this.transitionTo('posts.post', firstPost);
    	});
	}
}	

});

I would like to know if this is a good solution or if there is a better way to do this.

Thanks in advance!

Best, Vivek

App.Post.find(1) means “find the post with ID=1”. The first post might not have ID=1. You should use the firstObject property of the posts record array.

Instead of checking the isLoaded property, you can use the posts record array as a promise, and call .then() on it.

You probably don’t want to keep the /posts URL in the browser history, so you should use replaceWith instead of transitionTo, which will use history.replace() = better UX in this case. (But it only works with location: 'history' set on the router, i.e. not the default hash.)

Finally, I would also put that logic in the posts.index route instead of the posts route. You can use the activate hook, which is called once when a route is entered. You only want to do this logic in the posts.index route, not in all the post route, which is also a child route of posts.

Final result:

App.PostsIndexRoute = Ember.Route.extend({
    activate: function() {
        var self = this,
            posts = this.modelFor('posts');
        posts.then(function() {
            self.replaceWith('post', posts.get('firstObject'));
        });
    }
});

I hope it helps :slight_smile:

Hi Sebastian, thank you for your response.

However I could not get your solution to work. I enabled location history as suggested and used the route you provided. I get an error “No route found for URL” for any URL that I enter in the browser.

Any thoughts??

many thanks…

Can you link to a JSFiddle or JSBin?