Backbone-relational cannot instantiate two RelationalModel objects
Asked Answered
S

1

7

I am trying to implement BackboneRelational and keep getting

"Cannot instantiate more than one Backbone.RelationalModel with the same id per type!"

class App.Models.User extends Backbone.RelationalModel
  urlRoot : '/api/users'
  idAttribute: 'id'

  relations: [
    type: Backbone.HasMany
    key: 'plots'
    relatedModel: 'App.Models.Plot'
    collectionType: 'App.Collections.Plots'
    includeInJSON: false
    reverseRelation:
      key: 'user_id',
      includeInJSON: 'id'
  ]


class App.Models.Plot extends Backbone.RelationalModel
  urlRoot : '/api/plots'
  idAttribute: 'id'

If I switch one of the models to extends Backbone.Model I can instantiate both, but I get all the warnings that the relational functionality is broken..

I am trying to achieve the following:

 plot = new App.Models.Plot({id : 700})
 plot.fetch()
 plot.get('user')

What am I missing?

Steele answered 1/9, 2012 at 1:11 Comment(0)
R
10

The general idea behind the "one model per id" situation is that Backbone Relational uses a data store (Backbone.Relational.store) to eliminate repeated requests for models that have already been loaded.

Fortunately, it also provides a few helpers to help access models through the store. Instead of supplying an ID and fetching the plot, you might instead use the findOrCreate method you'll find attached to App.Models.Plot:

plot = App.Models.Plot.findOrCreate(700)
user = plot.get('user')
Roomy answered 1/9, 2012 at 1:29 Comment(3)
thanks! I can instantiate the plot now, but user = plot.get('user') returns undefined.Steele
You bet! The relation issue may be something else. Check out the coffeescript/setup Q+A at: github.com/PaulUithol/Backbone-relational#q-and-aRoomy
I see.. so after reading this, I conclude I just have to include App.Models.User.setup() as the last line of model code? Sorry, but can't quite figure it from the explanation there.. I can do plot.fetchRelated('user_id') though with the .setup() fix but not the get('user')..Steele

© 2022 - 2024 — McMap. All rights reserved.