Ember Version: 2.8.3
Ember Data Version: 2.8.1
I am getting an error when iterating through a hasMany relationship on an Ember-data model.
TypeError: Cannot read property 'get' of undefined
Here is the code that is getting the error:
question.get('question-options').then(options => {
options.forEach(option => {
option.destroyRecord();
});
});
question.set('kind', target.value);
A little background on the code. The question has a type and we remove the associated question-options when changing the type. In reality this is only happening to non-persisted questions (no id present).
In the above code if I replace option.destroyRecord()
with console.log(option.get('text'))
. Things work fine.
I can also get things to work they way I want them to by adding toArray()
before the forEach
. This is what I'm doing as a work-around but I wanted to see if anyone had any ideas why it was behaving this way.
question.get('question-options').then(options => {
options.toArray().forEach(option => {
option.destroyRecord();
});
});
question.set('kind', target.value);
Well, thats expected behavior. The problem is that the options
-hasMany
-array is a live-array. So it's updated whenever you add or remove data from the store. And thats what you're doing with destroyRecord
. So you are basically modifying the array while looping through it. And this will mess up with forEach
/is just not supported.
what also would work is something like this I think (but also not reliable):
while(options.get('firstObject')){
options.get('firstObject').destroyRecord();
}
I think going with toArray
is the right solution.