Search code examples
javascriptjsonember.jsember-dataember-app-kit

EmberJS Cannot set property 'store' of undefined (DS.hasMany)


Firstly I have read the related issues on SO and none seem to help me.

I have 2 models, Foo and Bar. Foo has a property, bars, which hasMany Bar.

// FOO

export default DS.Model.extend({
  name: attr('string'),
  bars: hasMany('bar')
});

// BAR

export default DS.Model.extend({
  name: attr('string')
  foo: belongsTo('foo')
});

And the JSON payload:

{
  "name": "Something",
  "bars": [
    {
       "name": "something else"
    },
    {
       "name": "another one"
    }
  ]
}

I've been trying to figure this error out for a while but I am stuck.

Here is the jsbin. If you look in the browsers console (not the jsbin one) you can see the error.


Solution

  • It looks like you are not specifying an ID for your "bar" objects. Each model needs an ID to make the object unque and know how to relate that to a resource. Changing your server output to the following should solve the issue:

    {
      "name": "Something",
      "bars": [
        {
           "id": 1,
           "name": "something else"
        },
        {
           "id": 2,   
           "name": "another one"
        }
      ]
    }
    

    Another solution (IDs should really be there regardless) is to set "async" to true as follows:

    export default DS.Model.extend({
      name: attr('string'),
      bars: hasMany('bar', { async: true })
    });
    

    This will cause EmberJS to load the data in the background and not block/causes errors with anything waiting on relationship resoltion.