Backbone-relational icon indicating copy to clipboard operation
Backbone-relational copied to clipboard

Update backbone-relational.js

Open ppecio opened this issue 11 years ago • 1 comments

Assume, that I have model Zoo with relation to animals. If I use save() method with wait: true to update & save the model and provide new animals as a list of IDs (like {animals: [1,23,43]} ), toJSON method in backbone-relations.js fails on value = value.concat(rel.keyIds), because value is null.

This is because Backbone does not use set() method in save() if wait is True - it's only make a simple copy of provided attributes and set as model's attributes. The relation (that is an attribute of course) is not initialized so is not a model (for HasOne relation), or Collection (for HasMany relation), but contains simple value like Number, String or Array (depends on the type of relation and the data I set), which are keys for relation.

This pull request fix this bug and add additional check to toJSON method. If relation value is not a model or collection and is not empty assume that is a raw data and should be returned "as is". toJSON method returns list of related object keys, I used a related object keys in attributes object for Backbone.save() method, so everything is OK.

ppecio avatar Oct 28 '14 14:10 ppecio

Wouldn't you have the same issue if includeInJSON were true or an array (the other two cases in toJSON)? And could you add a test case for this change?

PaulUithol avatar Oct 30 '14 16:10 PaulUithol