From reading the docs, it looks like you have to (or should) assign a model to a route like so:
App.PostRoute = Ember.Route.extend({
model: function() {
return App.Post.find();
}
});
What if I need to use several objects in a certain route? i.e. Posts, Comments and Users? How do I tell the route to load those?
https://stackoverflow.com/a/16466427/2637573 is fine for related models. However, with recent version of Ember CLI and Ember Data, there is a simpler approach for unrelated models:
If you only want to retrieve an object's property for
model2
, use DS.PromiseObject instead of DS.PromiseArray:Using
Em.Object
to encapsulate multiple models is a good way to get all data inmodel
hook. But it can't ensure all data is prepared after view rendering.Another choice is to use
Em.RSVP.hash
. It combines several promises together and return a new promise. The new promise if resolved after all the promises are resolved. AndsetupController
is not called until the promise is resolved or rejected.In this way you get all models before view rendering. And using
Em.Object
doesn't have this advantage.Another advantage is you can combine promise and non-promise. Like this:
Check this to learn more about
Em.RSVP
: https://github.com/tildeio/rsvp.jsBut don't use
Em.Object
orEm.RSVP
solution if your route has dynamic segmentsThe main problem is
link-to
. If you change url by click link generated bylink-to
with models, the model is passed directly to that route. In this case themodel
hook is not called and insetupController
you get the modellink-to
give you.An example is like this:
The route code:
And
link-to
code, the post is a model:Things become interesting here. When you use url
/post/1
to visit the page, themodel
hook is called, andsetupController
gets the plain object when promise resolved.But if you visit the page by click
link-to
link, it passespost
model toPostRoute
and the route will ignoremodel
hook. In this casesetupController
will get thepost
model, of course you can not get user.So make sure you don't use them in routes with dynamic segments.