0

In the following code, I establish 3 has-many/belongs-to relations.

Category > Subcategories > Items

Category.js.coffee:

class App.Models.Category extends Backbone.RelationalModel
  relations: [{
        type: Backbone.HasMany
        key: 'subcategories'
        relatedModel: 'App.Models.Subcategory'
        collectionType: 'App.Collections.Subcategories'
        reverseRelation: {
            key: 'category',
            includeInJSON: 'id'
        }
    }]

App.Models.Category.setup() # Set up BB Relational

Subcategory.js.coffee:

class App.Models.Subcategory extends Backbone.RelationalModel
  relations: [{
      type: Backbone.HasMany
      key: 'items'
      relatedModel: 'App.Models.Item'
      collectionType: 'App.Collections.Items'
      reverseRelation: {
          key: 'subcategory',
          includeInJSON: 'id'
      }
  }]

App.Models.Subcategory.setup() # Set up BB Relational

Item.js.coffee

class App.Models.Item extends Backbone.RelationalModel
   initialize: ->
    ...
App.Models.Item.setup() # Set up BB Relational

Problem:

Calling item.get('subcategory') works as expected, returning a Backbone RelationalModel object. However, for some reason calling category returns a generic JS object.

item.get('subcategory').get('category')

Returns: Object {id: 1, title: "the title"}

In case it's related, console.log @subcategory.relations shows the message "collectionKey=subcategory already exists on collection=true ".

pws5068
  • 2,224
  • 4
  • 35
  • 49
  • If its returning a generic js object, there is definitely something wrong with setting up BB – TYRONEMICHAEL Nov 23 '12 at 08:57
  • I'm suspicious that perhaps the reverse relationship from Categories -> Subcategories is affecting the defined relations in categories? – pws5068 Nov 23 '12 at 16:58

1 Answers1

0

Solved!

Backbone-Relational addresses an issue with coffeescript extends syntax by using the setup() methods as shown above.

My problem here was that my Category.js.coffee was being initialized before my Item.js.coffee so the setup() call's reverse relation could not be added to the model.

To fix this, I moved all of the setup() calls to my backbone initializer (once all objects were defined) in order of relation dependencies:

window.App =
  init: (options) -> 
    # Set up BB Relational
    GearSwap.Models.Item.setup()
    GearSwap.Models.Category.setup()
    GearSwap.Models.Subcategory.setup()
pws5068
  • 2,224
  • 4
  • 35
  • 49