Accessing attributes of related models in the controller - ember.js

I'm been asking a few questions around the same sort of lines and haven't managed to get an answer (perhaps I've been unclear), and just can't figure it out myself.
The quick version of the question is:
Can anybody shed some light on whether its possible to access a property of a related model from a controller?
Its a little tricky, so I'll try and explain the context.
I have the following models:
student
scores: DS.hasMany('score', {async: true}),
name: DS.attr('string')
objective
name: DS.attr('string'),
scores: DS.hasMany('score', {async : true})
score
scoreResult: DS.attr('number'),
objective: DS.belongsTo('objective', {async: true}),
student: DS.belongsTo('student', {async: true})
In my template, I can access attributes of related models with no problem. For example, something like this:
{{#each student in model}}
{{student.name}}
{{#each score in student.scores}}
{{score.objective.name}}
{{score.Result}}
{{/each}}
{{/each}}
What I ultimately want to do is create a "score" property on the student controller that loads the appropriate score/result when I choose an objective elsewhere. But I'm falling at the first hurdle.
Though I can access attributes of related models in the templates, I can't seem to in the controller. I'm expecting that I can do something like this in "student controller":
score: function(){
var selectedObjID = 5;
return this.get('model.scores').findBy('objective_id', 1).get('scoreResult');
I've tried every variation I can think of, including what I would have expected from reading the guides/api.
I feel like I'm missing something obvious - surely this should have been done enough before for there to be some documentation?
Its also important to do in the one route - I don't want details dealt with via another route.
--------------------------------Edit----------------------------
Thanks, I've tried adjusting your code a little, but I can't get it to work. Any chance you'd be able to help me correct it based on the model's above?
score: function() {
var scores = this.get('model.scores');
if (!scores) {
return "No scores";
}
var score = scores.findBy('objective', 1);
if (score === undefined) {
return "Not resolved/No score";
}
return score.get('scoreResult');
}.property('model.scores.#each.objective')

Though I can access attributes of related models in the templates, I can't seem to in the controller.
Based on this, I can take a good guess and say that your problem is unresolved promises. Ember Data doesn't always have synchronous access to related models, so it always returns a promise that will resolve later. More likely than not, you're trying to use that promise as if it's already resolved even though it's not yet. When writing computed properties based on Ember Data relationships, you should always write your properties as if you will be given empty data the first time through. Usually this means checking for null references and making sure the property updates when the promise resolves. To get to the point, here's your property that should work:
score: function() {
var scores = this.get('model.scores');
if (!scores) {
return;
}
var score = scores.findBy('objective_id', 1);
if (score === undefined) {
return;
}
return score.get('scoreResult');
}.property('model.scores.#each.objective_id')
The first time this property calculates this.get('model.scores') will be an empty PromiseArray, so you won't get any data from it. For those scenarios, just return and leave your property undefined (for now). But since the property is dependent on model.scores.#each.objective_id, the property will recalculate as soon as the PromiseArray resolves and the data is available. So this property won't have the right value until it runs 2 or 3 times, but it will eventually have the right value. The reason you don't get these issues when using the properties in a template is because Ember takes care of that for you.
Sorry for the long explanation, but there's a lot to learn in the area of unresolved promises and asynchronous computed properties (much more than I've posted). It's unfortunately one of those things that you just pick up as you learn Ember more. If I haven't made things clear or the above property doesn't work, let me know in the comments and I'll update and try to clarify.

Related

Ember Data 1.0.0-beta.11: How to find out if async relationship is empty?

I'm trying to update an app from Ember Data 1.0.0-beta.9 to 1.0.0-beta.11, and quite a bit seems to have changed. Specifically, I'm running into issues with finding out if a model instance does indeed have an associated model instance.
A = DS.Model.extend({
b: belongsTo('b', { async: true }),
});
B = DS.Model.extend({
a: belongsTo('a', { async: true }),
});
In Ember Data 1.0.0-beta.9, a.get('b') would simply return null if no associated model is found. That makes it easy to filter by computed property macros.
In Ember Data 1.0.0-beta.11, a.get('b') returns a promise, which makes it much harder to use in computed property macros. If the promise is fulfilled and the content of the promise is null, there's no associated record. But I have no idea whether it is possible to implement this check inside a Ember.computed.filter.
I have quite a few Ember.computed.filters probing quite a few Ember.isEmpty(a.get('b'))s, so I'm looking for a good way to check whether an object's async relationship is empty. Am I missing something obvious, like a built-in Ember Data api call? How would you implement such a check, if you need to filter by associated property presence/absence?
Well, to answer my own question, I got around this by filtering for Ember.isEmpty(a.get('b.id')), b/c I usually deal with persisted records and was able to ship around the edge cases. Sometimes it's so simple… :D
if the related record is just created and isNew is true, checking the id property would also return null. In my case this causes unexpected results. How I managed to overcome this is by checking the content property instead. For a newly created record this will return the model class, and null if the related object is empty.

Ember - How to deal with 2 models, in a single page, and with one model very slow to load?

Quite new to Ember, I'm building an app and encounter a difficult problem.
MY SITUATION
I have a single page, which should display a list of elements, named "containers", and inside each container, I want to display several "contents".
For now, here is a very simplified version of my JS code (just to give you an idea):
App.ContainersRoute = Ember.Route.extend({
model: function() {
return this.store.findAll('container');
}
});
App.Container = DS.Model.extend({
title: DS.attr('string'),
contents: DS.hasMany('content')
});
App.Content = DS.Model.extend({
[...]
});
I will pass on the template part, wich is not a problem here, it's quite classic.
So, this code is working, I have my list of containers, and a list of the propers contents for each of them.
MY PROBLEM = "A WHITE SCREEN OF DEATH"
Indeed, as I fetch my data from a server in JSON, for now, before Ember transitionning to my page, I have a wait the loading of all the data.
The problem is that, "containers" data is quite small and static, so my server can answer it in less than a second, but, for the "contents" part, it is very long (between 20 to 40 seconds), as my server needs to do a lot of work to recover these date from my DB.
It would be ok for me to wait this long if my page was already loaded (navigation + containers without the contents), but right now, I just have a white page during 30s with no idea except the console to know is everything is ok.
Of course, I could use a "loading bar" thanks to "beforeModel" in the Route, but I would very much prefer to have access at least to the UI.
FOR YOU, WHAT COULD BE A GOOD SOLUTION FOR THIS PROBLEM?
Thanks a lot in advance for your help :)
I'd make content's async and fetch that after the fact so you can give a more responsive look and feel.
App.Container = DS.Model.extend({
title: DS.attr('string'),
contents: DS.hasMany('content', {async: true})
});
App.Content = DS.Model.extend({
[...]
});
That means Ember Data will make a callback for that data when requested, and not expect it at the same time as the container data.
Example: http://emberjs.jsbin.com/OxIDiVU/1045/edit
Additionally you can add a loading route in the resource above your Containers resource which could give feedback about how your fetching data. http://emberjs.com/guides/routing/loading-and-error-substates/
Example: http://emberjs.jsbin.com/cerid/2/edit
Personally I like the async idea more though, show the fact that you have containers, but then show contents as loading/empty.

Handle rejected promise when Ember Data hasMany property is accessed by template

Is there a standard way of handling errors when a 'findHasMany' call fails? Use case:
Model: App.User
{
DS.hasMany('comments', {'async': true});
}
Template
{{#each comment in comments}}
<p>{{comment.title}}</p>
{{/each}}
The issue is that when the lazy loading of comments fails, due to some server issue for example, I want to be able to respond to that error in the UI (by routing somewhere else, showing a popup about errors on the page, etc). At the moment the promise just rejects. I thought that Ember Data might have some hook on the ManyArray for cases like this, but it doesn't seem to, and the store seems to define precisely nothing as the action to carry out in such cases: https://github.com/emberjs/data/blob/v1.0.0-beta.8/packages/ember-data/lib/system/store.js#L1758 - the promise is given a 'resolve' method, but not a reject method.
My options seem to be either subclassing the store, and adding in some reject code there, or subclassing DS.PromiseArray and observing the 'isRejected' property. Any thoughts would be very welcome!
EDIT:
This issue seems to boil down to the fact that, when handling models defined in a route, Ember and Ember Data work well together (you can catch rejecting promises in an error action) there is no similar structure for async requests directly through a template. One solution might be to have an observer in the controller that observes something like 'model.isError', but a failing hasMany relationship does not trigger an error on the owning model. I suppose instead I can do 'comments.isRejected', but again, I would have to code that in for every controller that has a model with a hasMany relationship, in other words, all of them, which doesn't seem very satisfactory. If models had an observable enumerable property (like "hasManyIsError": {comments: false, posts: true}) then it would be easy to observe any of them with 'hasManyIsError.length
Assuming a var called user that has been fetched, you'd do this:
var itWorked = function(comments) { return comments; }
var itFailed = function(error) { return error; }
user.get("comments").then(itWorked, itFailed);
async: true means it'll get using a promise... so you can use then... you can't do that on a relationship that doesn't specify async: true.
[edit] sorry I just realised it might not be obvous that whatever you put in the itFailed function will eval when the request for comments fails, and likewise inversely for itWorked... :)

A way to make all index route models = resource route model?

UPDATE
Okay, what luck…this is now the default behavior as of Ember 1.5. Yay!
Original question
Something that really seems intuitive to me but isn't the case in the Ember router. I have a bunch of resources, the vast bulk of which have an index route where I want the model to be the same as the resource route's model--that is, the object selected by convention using the dynamic segment. E.g.:
this.resource("chargeRule", { path: "/chargeRule/:chargeRule_id" }, function(){});
I'm going to be using nesting, so I can't do everything in my chargeRule template, because that template is going to have little but {{outlet}} (kinda like this guy). So my index route is going to be my read-only view in most cases and I'll have an edit sub-route to update a model where needed.
What bugs me is, the default model for an index route (and any other sub-route) is: NOTHING! Tada! Null I think, though it could be empty string or something. So, I now have to create a bunch of tiny Ember.Route subclasses that look exactly like this:
App.ChargeRuleIndexRoute = Ember.Route.extend({
model: function() {
return this.modelFor('chargeRule');
}
});
Repeat ad-nauseum for each different model class/route. Really, then about double it because I want the same for /index and /edit routes, maybe more. Personally, I would have thought that the default model (since you can override it anyway) for any child route should have been the parent route's model instead of nothing, but I'd be interested in explanations as to why it's not.
But my question is, can anybody come up with a way for me to make the behavior I'm describing the default in my app? Something I can reopen? So I don't have a dozen or more boilerplate 5-line route objects?
Edit
I might should mention that I know my gripe might seem trivial, but the fact that I have to create so many route subclasses also implies that I should create individual files for each class…right? So that future developers can easily find where a given class is defined? I know that's not an absolute, but is a good practice, I think, and would require me to make as many tiny JS files as tiny classes…which is why I started thinking in terms of changing the default behavior. I'll take comments on that though.
UPDATE
See note at top of question, this is no longer necessary...
Based on #kingpin2k 's answer, I came up with this more generalized possibility:
App.ParentModelRoute = Ember.Route.extend({
model: function() {
return this.modelFor(this.get('routeName').replace(/\..*$/, ''));
}
});
App.ChargeRuleIndexRoute = App.ParentModelRoute.extend();
App.ChargeRuleEditRoute = App.ParentModelRoute.extend();
App.OtherIndexRoute = App.ParentModelRoute.extend();
.
.
.
Which certainly cuts down on the amount of code…but still requires me to explicitly declare a route class for each sub-route. It also may be a bit hacky (the routeName property isn't listed in the API docs?), though it's simple enough it should work pretty widely.
The reason is due to the fact that a route doesn't necessarily have to contain a model. Think of the case of a Albums/New route. It wouldn't actually have the albums resource as its model. For this reason there is no set rule for what the model should be for a model.
That being said, if you feel like lazily building up some sort of default route for your route and extending this, that's entirely possible and can be accomplished a few different ways.
App.DefaultChargeRuleRoute = Ember.Route.extend({
model: function() {
return this.modelFor('chargeRule');
}
});
App.ChargeRuleIndexRoute = App.DefaultChargeRuleRoute.extend();
App.ChargeRuleEditRoute = App.DefaultChargeRuleRoute.extend();
or if you wanted to make some generic model fetching route
App.ModelFetcherRoute = Ember.Mixin.create({
model: function(){
return this.modelFor(this.get('modelToFetch'));
}
});
App.ChargeRuleIndexRoute = Ember.Route.extend(App.ModelFetcherRoute, {
modelToFetch: 'chargeRule'
});
And this could follow the same pattern as the first example if you want to make it even smaller
App.DefaultChargeRuleRoute = Ember.Route.extend(App.ModelFetcherRoute, {
modelToFetch: 'chargeRule'
});
App.ChargeRuleIndexRoute = App.DefaultChargeRuleRoute.extend();
App.ChargeRuleEditRoute = App.DefaultChargeRuleRoute.extend();

Passing parameters between routes

What is the "appropriate" way in Ember to send a parameter from one route to another? For instance, I have two routes defined as such:
this.resource('activities', { path: '/activities/:on_date' }, function() {
this.route('new');
});
when on the ActivitiesRoute the user is presented with a dropdown of possible activities. When they choose something it transitions to the ActivitiesNewRoute:
this.transitionToRoute('activities.new');
and I know there is a second parameter available in the transitionToRoute(route,model) method but it's meant for passing in a model and I'm assuming this shouldn't be repurposed for other parameter passing. In this case the dropdown choice is picking an Action model id and the model for ActivitiesNew is a Activity.
Here are my three guesses at ways that might work:
1) Make it a router parameter
I supposed I could change ActivitiesNew to include a "parameter" as part of the route:
this.route('new', { path: '/new/:my_parameter' });
I'm not sure I'd really like to have it becoming part of the URL path but if this was the prevailing convention then I'd live with that.
2) Get a handle, post transition
Immediately following the transitionToRoute call I could set a property of the new controller class. Not sure if the controller would be setup yet but I'm imagining something like:
this.transitionToRoute('activities.new');
this.get('target').controllerFor('activities.new').set('my_parameter', myValue);
3) Use model parameter
this.transitionToRoute('activities.new',myValue);
I suspect that this is a major no-no. I haven't looked into the Ember code to know if this could work but it seems against convention so this is my "bad option".
transitionTo & transitionToRoute return a "promise-like" object. The parameter this object is resolved with is the route, from which you can access controller and currentModel. So a nice clean way to pass information to a route to which you are transitioning is:
var my_param = ....;
this.transitionToRoute('activities.new').then(function(newRoute) {
newRoute.currentModel.set('someProperty', my_param);
//or
newRoute.controller.set('someProperty', my_param);
});
EDIT/RANT:
note that in most cases, you do want to use needs, and bind things between controllers. However, there are certainly instances when you have things that depend on the logic of a route transition -- eg., controllerB has state X if we came to routeA from routeB, but state Y if we came from routeC. In that case, my answer is valuable.
The primary value of stack overflow to the development community is not the immediate answers you get to questions you post, but the massive ever growing wealth of googleable development knowledge. When you "infer" from a user's question that they "should" be doing something other than what they are asking how to do, you may be right (or you may be just incapable of imagining their particular circumstance), but if you answer only with your recommendation/rule/aphorism/cargo-cult-dictum instead of answering the ACTUAL QUESTION, you diminish the value of everybody else's google searches. If you want to tell someone to do something other than what they're asking, do it in a comment, or in a footnote to an answer to the actual question.
You can use the needs API (Read about it here):
App.ActivitiesNewController = Ember.ObjectController.extend({
needs: ['activities']
// Bind the property you need
actionTemplateBinding: 'controllers.activities.actionTemplate'
});
So what you actually need is to pass a parameter between controllers, which is exactly what needs is for. Plus, binding the property with needs you ensure it is in sync at all times, instead of relying on setupController being called.
You could use query-params (http://guides.emberjs.com/v1.10.0/routing/query-params/), as follows:
this.transitionToRoute('activities.new', {queryParams: {my_param: 'my_value'});
In order to be able to receive my_param in the new controller, you would also need to define the following lines:
App.ActivitiesNewController = Ember.ObjectController.extend({
queryParams: ['my_param'],
my_param: ''
...
});
A drawback of this solution is that the value of my_param will be serialized in URL - so it would not be suitable for some sensitive information you may want to pass between routes.
I'll answer my question with what I've decided to go with for now but keep it open for a a few days to see if anyone comes back with a more experienced answer. My answer may very well be perfectly fine ... it works anyway.
I've gone with a variation of #2 from the question. The difference is that that rather than trying to set a property in the ActivitiesNew controller from Activities controller I do the the opposite:
In ActivitiesNewRoute:
App.ActivitiesNewRoute = Ember.Route.extend({
model: function(params) {
return this.store.createRecord('activity');
},
setupController: function(controller,model) {
controller.set('actionTemplate', this.controllerFor('activities').get('actionTemplate'));
}
});
Still interested in hearing from people if there's a better way of doing this.
Transition to route with params and set model
yourAction:->
model = 'your-model'
route = 'your.path.to.toute'
routeLoad = #transitionToRoute route,
id: model.get 'id'
routeLoad.then (route) ->
route.set 'controller.model', model
return