Reputation: 339
I'm working on a simple Tag model for one of my projects. I've implemented something similar in Angular, but I wanted to give it a try in Ember. The model code is below
Tag = DS.Model.extend {
name:DS.attr('string')
user:DS.belongsTo('user')
appliedTags:DS.hasMany('AppliedTag')
obliterate:()->
#destory the associated applied tags
this.get('appliedTags').forEach( (appliedTag)->
console.log(Ember.inspect(appliedTag))
appliedTag.destoryRecord()
)
#destory the record
this.destroyRecord()
}
fixtures = [
id:1
name:'Category 1'
user:1
appliedTags:[1,5]
]
Tag.reopenClass
FIXTURES: fixtures
Everything is fine if I comment out appliedTag.destoryRecord()
. However with it in, on the second time through the forEach
loop, appliedTag
is undefined.
Upvotes: 4
Views: 310
Reputation: 47367
Modifying the contents of a collection while iterating will cause major issues. That's the issue that you're seeing here, you're destroying records, which modifies the collection that's being iterated. Ember's hasMany collection will remove records when they are removed from the store/destroyed. The easiest solution is to copy the contents to a different array that won't get modified when you perform those kinds of operations.
this.get('appliedTags').toArray().forEach( (appliedTag)->
console.log(Ember.inspect(appliedTag))
appliedTag.destoryRecord()
)
Upvotes: 6