Iterate through hasMany / belongsTo relation in ObjectController

I want to return the child elements (notes) of a given draft (parent element) as a computed property from my Ember.DocumentController. In this case I want to return all the notes that belong to the editableDraft property.

Or is there a better way of doing it?

App.DocumentController = Ember.ObjectController.extend({
  editableDraft: function() {
    var editDrafts = this.get('model.drafts').filterBy("editable", true);
    var draft = editDrafts.length ? editDrafts[0] : null;
    return draft;
  }.property('model.drafts.@each.editable'),
  editableNotes: function() {
    var eDraft = this.get("editableDraft"); // want to return notes of editableDraft
    return eDraft.get("notes");
  }.property('model.drafts.@each.editable')
});

See test app in the jsbin!

Based on some of the feedback from @alexspeller here, it seems that it might make sense to put those drafts in a separate controller. In your route’s setup controller hook, maybe something like this:

setupController: function(controller, model) {
  controller.set('model', model);
  this.controllerFor('drafts').set('model', model.get('drafts'));
}

Then, your controllers:

App.DraftsController = Ember.ArrayController.extend({
  editable: Em.computed.filterBy('@this', true)
});

App.DocumentController = Ember.ObjectController.extend({
  needs: ['drafts'],
  drafts: Em.computed.alias('controllers.drafts'),
  editableDraft: Em.computed.alias('drafts.editable.firstObject')
});
2 Likes

I managed to get it to work like this jsbin qajecivo/31/edit (I’m not allowed to post links?) but I’m aware that there must be better implementations for this. I’ll keep your twist @alexspeller’s output for this in mind! Thank you!