Nested relations and json parsing #452

Closed
karellm opened this Issue Apr 11, 2014 · 1 comment

Projects

None yet

3 participants

@karellm
karellm commented Apr 11, 2014

Hi,

I am struggling with a simple use case. The API I plug to return the following json for a contractor:

{
    "id": "3",
    "email": "bla@bla.bla",
    "services": [
        {
            "id": "1", 
            "name": "bla", 
            "locations": ["12"]
        }
    ]
}

So I define couple relations.

# in the contractor model:
relations: [
        type: Backbone.HasMany
        key: 'services'
        relatedModel: App.Models.Service
        collectionType: App.Collection
]

# in the service model:
relations: [
    type: Backbone.HasMany
    key: 'locations'
    relatedModel: App.Models.Location
    collectionType: App.Collection
    includeInJSON: Backbone.Model.prototype.idAttribute
]

But it throws the following error:

Relation=
child
: missing model, key or relatedModel (function Service() {
    return Service.__super__.constructor.apply(this, arguments);
  }, "locations", undefined). 

I also realized that doing something like:

new Contractor({
    "id": "3",
    "email": "bla@bla.bla",
    "services": [
       'id_not_already_loaded'
    ]
})

generates a Contractor model with an empty services collection. Why is that? I would expect a collection with one Service model that only has the id as an t

@dminkovsky

The first part of this issue appears to be a circular dependency problem? I've found these issues can be simplified by defining your models on one object (even window), making sure that object is defined as a modelScope in Backbone.Relational.store (http://backbonerelational.org/#Store) and then using strings instead of objects as references in relation definitions. It's not pretty, but it works better given the whole model/collection circular dependency problem that ensues.

Re: the second question on this issue: yes, for a HasMany relation, you need to specify an array of already loaded IDs or an array of objects. If you specify an id_not_already_loaded, it won't be included in the related collection until its fetched.

@bpatram bpatram added the question label Mar 16, 2016
@bpatram bpatram closed this Mar 16, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment