3
votes

I am trying to initialize a Route's model with a DS query, as follows

App.Router.map(function() {
    this.resource('post', { path: '/posts/:post_slug' });
});

App.PostsRoute = Ember.Route.extend({
    model: function(params) {
        var records = App.Post.find({ slug: params.post_slug });
        return records.get('firstObject');
    }
});

Here, i find a Post by its slug and set the first result as the route model. but since records is populated asynchronously, the model data is not set properly. What is the correct way to do this?

2

2 Answers

7
votes

Solved this with Deferred pattern.

App.PostsRoute = Ember.Route.extend({
    model: function(params) {
        var records = App.Post.find({ slug: params.post_slug });
        var promise = Ember.Deferred.create();
        records.addObserver('isLoaded', function() {
            promise.resolve(records.get('firstObject'));
        });
        return promise;
    }
});
0
votes

That should do that trick:

App.Router.map(function() {
  this.resource('posts');
  this.resource('post', { path: '/posts/:post_id' });
});

App.PostsRoute = Ember.Route.extend({
  model: function() {
    return App.Post.find();
  }
});

App.PostRoute = Ember.Route.extend({
  model: function(params) {
    return App.Post.find(params.post_id);
  }
});