1
votes

So I have an ember-cli 1.13.8 application where I would like to view the questions without answers. Currently, I can filter searches based on attributes. For example, I can search for the "content" of questions because that is an attribute on the object.

Models:

answer:

export default DS.Model.extend({
  ...
  content: DS.attr(),
  question: DS.belongsTo('question', { async: true })
});

questions:

export default DS.Model.extend({
  ...
  answers: DS.hasMany('answer', { async: true }),
});

For example, this works to query attributes of the current model (question):

model(query) {
 return this.store.findAll('question').then(function(questions) {
   return questions.filterBy("content", query);
 });
}

But I cannot filter based upon the properties (in this case length) of the attributes of the model. I would like to filter based upon those questions which have no answers.

model() {
  return this.store.findAll('question').then(function(questions) {
    return questions.filter(function(item, index, enumberable) {
      return item.answers.length === 0;
    })
  });
}

Another attempt:

model() {
  this.store.findAll('question').filter('question', function(q) {
    return q.get('answers.length') === 0;
  })
}

I have consulted: Emberjs filter() versus filterProperty()

It seems that filterProperty() has been deprecated so examples such as: http://www.kaspertidemann.com/how-to-filter-an-array-of-records-by-a-property-value-in-ember-js/ are not helpful.

1

1 Answers

3
votes

The problem is that the answers the answers relationship hasn't been loaded. The way I would do it is leave the route responsible for fetching the models and leaving the controller responsible for displaying the data.

In the route where you want to filter out questions with no answers:

model() {
  return this.store.findAll('question').then( (questions) => {
    let promiseArray = questions.map( (question) => {
      return question.get('answer');
    })

    return Ember.RSVP.all(promiseArray);
  });
}

In the controller filter the models:

filteredModels: Ember.computed('model.[]', function() {
  return this.get('model').filter( (question) => {
     return question.get('answers.length') === 0;
  })
})