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?

Stpn
  • 6,202
  • 7
  • 47
  • 94

1 Answers1

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')
rjz
  • 16,182
  • 3
  • 36
  • 35
  • 1
    thanks! I can instantiate the plot now, but user = plot.get('user') returns undefined. – Stpn Sep 01 '12 at 01:37
  • You bet! The relation issue may be something else. Check out the coffeescript/`setup` Q+A at: https://github.com/PaulUithol/Backbone-relational#q-and-a – rjz Sep 01 '12 at 01:39
  • 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').. – Stpn Sep 01 '12 at 02:01