0

I have two objects as follows:

AC.Category = DS.Model.extend({
  name: DS.attr('string'),
  order: DS.attr('number'),
  subcats: DS.hasMany('AC.SubCategory')
});

AC.SubCategory = DS.Model.extend({
  name: DS.attr('string'),
  order: DS.attr('number'),
  category: DS.belongsTo('AC.Category')
});

I'm trying to output all the categories in order (by their 'order' properties) via my IndexRoute. So the code looks something like this:

AC.IndexRoute = Ember.Route.extend({
  model: function() {
    return AC.Category.find();
  }
});

AC.IndexController = Ember.ArrayController.extend({
  sortProperties: ['order'],
  sortAscending: true
});

This sorts the top-level categories fine, but I can't figure out how to submit the sub-categories so I can output those in order.

How would I go about doing this in Ember, or should I just do it server-side and pass the data through the API already sorted?

1 Answer 1

1
AC.IndexController = Ember.ArrayController.extend({
  sortProperties: ['order'],
  sortAscending: true,

  // Use an Ember.ObjectController for each Category
  itemController: 'category'
});

App.CategoryController = Ember.ObjectController.extend({
  init: function() {
    this._super();

    this.set('subcategoriesController', App.SubcategoriesController.create({
      category: this
    }));
  }
});

App.SubcategoriesController = Ember.ArrayController.extend({
  sortProperties: ['order'],
  sortAscending: true,

  content: function() {
    return this.get('category.subcats');
  }.property('category.subcats.[]')
});

And then your index template should look like:

<ul>
  {{#each category in arrangedContent}}
    <li>
      {{category.name}}
      <ul>
        {{#each subcategory in category.subcategoriesController.arrangedContent}}
          <li>{{subcategory.name}}</li>
        {{/each}}
    </li>
  {{/each}}
</ul>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, really appreciate it. Would have been stuck on this for days.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.