Doe Johnson
Doe Johnson

Reputation: 1414

Ember: Cant access hasMany relation programmatically while it works in handlebars template?

First thing to mention, I'm pretty new to ember, especially to ember-data. So maybe I'm missing some essential noob-stuff here.

There are two models: Result and ResultSubset. A result can consist of multiple subsets.

result.js:

import DS from "ember-data";
var Result = DS.Model.extend({
  subsets: DS.hasMany("result_subset", {async: true})
  // ...
});
Result.reopenClass({
  FIXTURES: [{id: 1, subsets: [1, 2]}]
});
export default Result;

result-subset.js:

import DS from "ember-data";
var ResultSubset = DS.Model.extend( {
  result: DS.belongsTo("result", {async:true}),
  singleValue: DS.attr("number")
  // ...
});
ResultSubset.reopenClass({
  FIXTURES: [
    {id: 1, result: 1, singleValue: 21},
    {id: 2, result: 1, singleValue: 42}
  ]
});
export default ResultSubset;

Everything works as expected when I access the model from within a hbs template like this:

{{#each subset in result.subsets}}
    {{subset.singleValue}}
{{/each}}

On the other hand, when I try it programmatically (inside a view/component), subsets is undefined.

// ...
console.log(this.get("result")); // works
console.log(this.get("result").get("subsets")); // undefined
// ...

I'm running Ember 1.7 and ember-data 1.0.0-beta.9

What am I missing? Thanks in advance!

Upvotes: 0

Views: 85

Answers (1)

Steve H.
Steve H.

Reputation: 6947

You'll need to resolve your Result object like this:

this.get('result').then(function(resolvedResult) {
    resolvedResult.get('subsets').then(function (resolvedSubsets) {
        resolvedSubsets.forEach(function(subset) {
            console.log(subset);
        });
    }, function(subsetReject) { /* handle error here */ });
}, function (resultReject) { /* handle error here */ });

Remember that relationships in Ember are Promises, so you'll need to deal with that. Handlebars automatically resolves these relationships.

Upvotes: 1

Related Questions