Need ember model to return array promise not object

813 Views Asked by At

I am trying to return a array promise to my model so that I can loop through the results in my template. I need the contact products to return as an promise array and not a promise object.

Model :

App.ContactEditorRoute = Ember.Route.extend({
   model: function (params) {
    return Ember.RSVP.hash({
        contact: this.store.find('contact', params.id),
    /*need this to return array not an object which is currently does*/
        contactproducts: this.store.find('contactproduct',params.id),
        products: this.store.find('product') 
    })
}

Template: (using emblem for markup)

each contactproduct in contactproducts
      p
        ' quantity
        contactproduct.quantity
        ' notes
        contactproduct.note
1

There are 1 best solutions below

2
On BEST ANSWER

If you really want it to be an array with the way you have your code currently structured, then you can do

contactproducts: this.store.find('contactproduct',params.id)
    .then(product => [product])

This is an approach to take when you want to do some additional processing on the result of a find, yet still return a promise as model is designed to do.

However, as another poster indicated this is probably not what you want to be doing. If contact products are a hasMany property of contacts, then they will already be there (or perhaps fetched for you based on {async: true}).

If contacts has no hasMany('contactproduct'), then you may need to fetch them yourself, but I doubt if contact products have the same id as contacts. If they do, they shouldn't. model IDs should be unique. Assuming contact products have a belongsTo pointing back to contact then you want to do this:

contactproducts: this.store.find('contactproduct', { contact: params.id })

which will return a (promise for) an array.

However, in general in such cases it's better to put the additional retrieval in the afterModel hook. That allows you keep your model nice and clean.