New hasMany with async

I’ve recently started using Ember / Ember Data 1.0. I have a form for an object Foo which allows for the dynamic creation of children Bar as well. This works:

Model:

bars: DS.hasMany('bar')  

setupController:

model.get('bars').createRecord()

However if the hasMany is set to async I can’t add child records. This doesn’t work:

Model:

bars: DS.hasMany('bar', {async: true})

Route:

model.get('bars').createRecord()  
// Uncaught TypeError: Object [object Object] has no method 'createRecord'

This is because the attribute is no longer a ManyArray but a PromiseArray! I have tried overriding the attribute for the form to no effect:

model.set('bars', DS.hasMany('bar',{async: false}))

Interestingly this does create a new array (different ember id) but it is also a PromiseArray.

Any thoughts?

Take a look this https://github.com/FeipingHunag/ember-todo

Thank you @FeipingHunag for the example (and speedy response) - extremely useful. However I need to create the parent and children all in the same form. I finally accomplished this by building the children in an entirely separate ArrayController, assigning the parent model to the belongsTo attribute, and then saving the children after the parent has successfully saved (which picks up the new parent’s id).

I posted this here instead of StackExchange to raise the question - should a newly created model have a PromiseArray for a hasMany attribute? Maybe there’s something I don’t understand about promises at play here.

I tried many times using the async option. Tried today again. I was on a talk by @wycats and his slides showed something like:

{"post": {
    "id": 1,
    "_links": {
        "comments": "/post/2/comments"
    }
}}

This never works for me. I get a promise in place of the relationship and the promise is always fulfilled and no call to the server or to my adapter. Tested witho ember final and ember data beta.2. Also tested with canary builds from an hour ago.

This does work for me:

Adapter - DS.RESTAdapter

App.ApplicationAdapter = DS.RESTAdapter.extend
  namespace: 'api'

App.Store = DS.Store.extend
  adapter: App.ApplicationAdapter

Model - note ‘comment’ is singular inside hasMany

comments: DS.hasMany('comment', {async: true})

JSON response for Post:

{"post":{
  "id":1,
  "title":"Blog Post",
  "links":{
    "comments":"api/posts/1/comments"}}}

And then the call to ‘api/posts/1/comments’ is made automatically in the post show route (‘#/posts/1’).

“links” instead of “_links” works. /facepalm

thanks!

I think the plan is to follow http://jsonapi.org/ very closely. I have been modeling my servers JSON after the spec there and it has been working well.

1 Like