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

Duplicate id error for sub models with different types

Open jackocnr opened this issue 12 years ago • 1 comments

We've only just gotten around to upgrading Backbone-relational from v0.5, and we're getting Uncaught Error: Cannot instantiate more than one Backbone.RelationalModel with the same id per type! The problem is to do with instantiating 2 objects of different types that have the same id. The issue is that both of the objects are sub-models of the same super-model. I've created a CodePen here: http://codepen.io/jackocnr/pen/LGzAv

Update: I've just seen this section of the documentation: http://backbonerelational.org/#RelationalModel-subModelTypes where it says "Note that this means that there cannot be any overlap in ids between instances of Mammal and Primate, as the Primate with id 3 will be the Mammal with id 3". So I'm now wondering if there is any workaround for this situation? Could I tell the BBR store to use a different field for the ID, which includes the type or something? E.g. "user23", and "event23"? I've spent a bit of time trying to understand idAttribute and resolveIdForItem() but I haven't gotten anywhere yet.

The reason we have this situation is because we have some model types (User, Event etc) which are used around the site as completely independent objects, BUT then we have activity feeds (ActivityItem models) with a hasOne relationship to an ActivitySubject object, which could be anything - a User, an Event etc. Hence those objects extend the main ActivitySubject type. How do you propose we deal with this situation (assuming our backend system allows objects of different types (User, Event etc) to have the same IDs)?

Thanks for your help.

jackocnr avatar Mar 22 '13 05:03 jackocnr

Ok I got this working by setting an idAttribute on the parent object ActivitySubject to "relationalId", and then set parse method to copy the response.id to response.relationalId. To get this to work I have to make sure I set {parse: true} whenever I call findOrCreate() or new UserCollection() etc.

This seems less than ideal - if I accidentally miss a {parse: true} somewhere, things will start to break...

jackocnr avatar Mar 24 '13 23:03 jackocnr