Want to delete associated model with ember-data. I use a mixin when I want to implement this behaviour. My models are defined as follows:
1 2 3 4 5 6 7 8 9 10 11 12 | App.Post = DS.Model.extend(App.DeletesDependentRelationships, { dependentRelationships: ['comments'], comments: DS.hasMany('App.Comment'), author: DS.belongsTo('App.User') }); App.User = DS.Model.extend(); App.Comment = DS.Model.extend({ post: DS.belongsTo('App.Post') }); |
The mixin itself:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | App.DeletesDependentRelationships = Ember.Mixin.create({ // an array of relationship names to delete dependentRelationships: null, // set to 'delete' or 'unload' depending on whether or not you want // to actually send the deletions to the server deleteMethod: 'unload', deleteRecord: function() { var transaction = this.get('store').transaction(); transaction.add(this); this.deleteDependentRelationships(transaction); this._super(); }, deleteDependentRelationships: function(transaction) { var self = this; var klass = Ember.get(this.constructor.toString()); var fields = Ember.get(klass, 'fields'); this.get('dependentRelationships').forEach(function(name) { var relationshipType = fields.get(name); switch(relationshipType) { case 'belongsTo': return self.deleteBelongsToRelationship(name, transaction); case 'hasMany': return self.deleteHasManyRelationship(name, transaction); } }); }, deleteBelongsToRelationship: function(name, transaction) { var record = this.get(name); if (record) this.deleteOrUnloadRecord(record, transaction); }, deleteHasManyRelationship: function(key, transaction) { var self = this; // deleting from a RecordArray doesn't play well with forEach, // so convert to a normal array first this.get(key).toArray().forEach(function(record) { self.deleteOrUnloadRecord(record, transaction); }); }, deleteOrUnloadRecord: function(record, transaction) { var deleteMethod = this.get('deleteMethod'); if (deleteMethod === 'delete') { transaction.add(record); record.deleteRecord(); } else if (deleteMethod === 'unload') { var store = this.get('store'); store.unloadRecord(record); } } }); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.