mardi 11 août 2020

Ember Data creates duplicate record on model save() | ember-cli v3.19

Ember duplicates models on save. I have two models

**bill**

export default class BillModel extends Model {
    @attr("string", { defaultValue: "", uppercase: true })
    vehicleNumber;

    @attr("string", { defaultValue: "" })
    customerName;

    @attr("number", { defaultValue: "" })
    customerMobileNumber;

    @attr("date")
    createdOn;

    @hasMany("bill-item")
    billItems;

    @attr("number", { defaultValue: 0 })
    total;

    @computed(
        "billItems.@each.cost"
    )
    get computedTotal() {
        let total = 0;
        this.billItems.forEach((item) => {
            if (item.cost)
                total += parseFloat(item.cost);
        });
        return parseFloat(total);
    }
}


**bill-item**

export default class BillItemModel extends Model {
    @attr("string", { defaultValue: "" })
    itemName;

    @attr("number", { defaultValue: null })
    cost;
}

Then I create a new record of the "bill" model and create a "bill-item" record and add that in the billItems property of the bill model.

let bill = this.store.createRecord("bill");
bill.billItems.addObject(this.store.createRecord("bill-item"));

then when I use the save() the "bill" model, I now have two records in the billItems property. One with id returned from the server response and one with But I should have only one. Below is the server response.

{
  "vehicleNumber": "1231",
  "customerName": "123",
  "customerMobileNumber": 1231232312,
  "createdOn": null,
  "total": 23123,
  "billItems": [
    {
      "itemName": "1231",
      "cost": 23123,
      "id": "9510"
    }
  ],
  "id": 467
}

Why does the ember store now have 2 records of "bill-item" model when I tried to save only one? The adapter used for the models are RESTAdapter and serializer is JSONSerializer.

Ember inspector attachment for reference




Aucun commentaire:

Enregistrer un commentaire