Search code examples
ember-data

Ember-data creating extraneous record in memory


I have a many to many relationship table with payload (additional field) coming from .Net WebAPI that I have modelled in ember-data. When I add a record into this table/relationship ember is creating an additional record that is held in memory until the user performs a browser page refresh. My models are:

// student.js
export default DS.Model.extend({
    name: DS.attr('string'),
    studentsClasses: DS.hasMany('student-class')
})

// class.js
export default DS.Model.extend({
    desc: DS.attr('string'),
    studentsClasses: DS.hasMany('student-class')
})

// student-class
export default DS.Model.extend({
    studentId: DS.attr('string'),
    student: DS.belongsTo('student'),
    class: DS.belongsTo('class'),
    grade: DS.attr('number')  // payload
})

Here is the code I use to create and add the many to many record.

let newRecord = this.get('store').createRecord('student-class');
newRecord.studentId = 1;
newRecord.grade = 3;
class.get('studentsClasses').pushObject(newRecord);

The new record gets created and added and everything looks good on screen, until I come back to the same page and there is an extra record in the class.studentClasses array.

Any idea why ember-data is creating an extra record in memory and how I can stop it doing it please? Thanks


Solution

  • As you said, ember-data keeps records in memory. And you must keep in mind that ember-data will not remove those records by it own. It can only be removed from memory by yourself, page refresh or replaced by new payload if has same id property. You can observe that behavior by using ember debug plugin for browsers like chrome and firefox.

    In your case, you've created a new record by store.createRecord(). In this moment, it had added this record to your memory already, and it was pushed to your class record. If you didn't save these models successfully, it will keep in a status called 'dirty', and if you never clean your store memory (using something like store.unloadRecord() which has some side effects, or remove this unsaved new record from your related model), the next time you use store.findRecord() to find a record, useless you force record to be reloaded like store.findRecord('class', 1, {reload: true}), it will use the existing data in your memory as first priority.

    So my suggestion for this is to force reload this class model when entering this class page.