Reputation: 1580
I want to sort the records that I'm getting by date in descending order.
//model definition
export default DS.Model.extend({
name: DS.attr('string'),
date: DS.attr('number')
}
I tried return this.store.findAll('mymodel').sortBy('date')
but no success. I'm using version 2.3.0.
//the data
"mymodel" : {
"-KBJDc1Ccg2kny1Vzn5B" : {
"date" : 1456350696971,
"name" : "Jhon"
},
"-KBJH_JN6G-AiAVsRfCS" : {
"date" : 1456349784907,
"name" : "Peter"
},
"-KBK6ZaiI-6o6KPocrSJ" : {
"date" : 1456348227848,
"name" : "Paul"
}
}
Upvotes: 3
Views: 3712
Reputation: 18240
Returning this.store.findAll('mymodel').sortBy('date')
can't work because findAll
returns a PromiseArray!
If you do it in a model
hook you should do:
return this.store.findAll('mymodel').then(results => results.sortBy('date'));
And if you do it in a computed property you probably want to reencapsulate it in an PromiseArray:
list: Ember.computed({
get() {
let promise = this.store.findAll('mymodel').then(results => results.sortBy('date'));
return DS.PromiseArray.create({promise});
}
}
Upvotes: 5
Reputation: 194
As @Lux said, you can't sort your model in your route because is a promise, but you can sort it in your controller, adding a computed property.
Your route
will look like this:
model:function(){
return this.store.findAll('mymodel');
}
And your controller
will look like this:
sortingKey:['date'],
sortedModel:Ember.computed.sort('model', 'sortingKey')
Why the sort in the router?
Because when model is set in controller the promise is already resolved.
See:
https://stackoverflow.com/a/35624736/3998465 http://emberjs.com/api/classes/Ember.computed.html#method_sort
Upvotes: 1
Reputation: 981
I was just hit by this problem really hard, I just wanted to sort result of findAll() , would never expect to be so big issue.
Luckily friend adviced me to use https://www.npmjs.com/package/ember-composable-helpers sort-by helper, so in hbs in each i just switched original taskItems with (sort-by "name:asc" taskItems) , and magic was done.
Upvotes: 2