Skip to content

Collection#set uses un-parsed attribute id to determine uniqueness #3390

@bdusell

Description

@bdusell

Due to limitations in a backend API I am working with, I have a model class whose id attribute is generated by its parse method (it's simply moving a nested attribute up to the top level). I am fetching a collection which may contain models with already exist in the collection. Under normal circumstances, when merge: true is set, I would expect models with the same id to be merged together. However, this will not work when the id attribute is not present in the un-parsed json data, as you can see from the following code in Collection#set:

for (i = 0, l = models.length; i < l; i++) {
  attrs = models[i] || {};
  if (attrs instanceof Model) {
    id = model = attrs;
  } else {
    id = attrs[targetModel.prototype.idAttribute || 'id'];
  }

  // If a duplicate is found, prevent it from being added and
  // optionally merge it into the existing model.
  if (existing = this.get(id)) {

The workaround I have in mind is to override parse in my collection class, and although this will work just fine, it feels a bit unclean and requires some code duplication. Would you consider moving the parsing stage to before the id check? All branches of execution eventually parse the model.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions