relational FetchRelated doesn't fetch anything

Trying to put together a backone solution to clean messy javascript, ends up to be a painful endeavour. Surely I'm doing something wrong, but cannot find any solution. the data contains many garages that have nested model CarsType with following attributes(name,description). Each carType are used once per garage but can be found in many garages. carType are sorted arbitrary per garage so the relation table car_type/garage name pack is defined this way | id | garage_id | car_type_id | position |

Each carType are assign to many mechanics. each mechanic can work in many garages. so the third nested level is a relation table mechanic_pack |mechanic_id|pack_id|

Backend is rails 3.1 that spits out Json.

Garage = Backbone.RelationalModel.extend({
    relations: [
        {
            type: Backbone.HasMany, 
            key: 'Packs',
            relatedModel: 'pack',
            collectionType: 'Packs',
            reverseRelation: {
              key: 'garage',
                includeInJSON: 'id' 
            }
        }
    ],

    initialize: function(attributes) {
        this.fetchRelated("packs");
      },

    url : function() {
      var base = 'garages';
      if (this.isNew()) return base;
      return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
    }
///... more method ...

});

packs collections is defined in another file

Packs= Backbone.Collection.extend({
    model: Pack, 
    url: '/packs/list/:garage_id'
});

model gets loaded correctly but fetchRelated doesn't fetch and doesn't throw any errors. Breakpoint in Firebugs shows that toFetch is always undefined

fetchRelated: function( key, options ) {
  options || ( options = {} );
  var rel = this.getRelation( key ),
  keyContents = rel && rel.keyContents,
  toFetch = keyContents && _.select( _.isArray( keyContents ) ? keyContents : [ keyContents ], function( item ) {
  var id = _.isString( item ) || _.isNumber( item ) ? item : item[      rel.relatedModel.prototype.idAttribute ];
  return id && !Backbone.Relational.store.find( rel.relatedModel, id );
  }, this );
  if ( toFetch && toFetch.length ) { 
......

How should I invoke fetchRelated?

2nd question: When a garage is requested rails sends the full tree of nested models. is there a way to populate backones nested models from the initial json answer? and be able to manipulate each nested model with their own view?


  initialize: function(attributes) {
    this.fetchRelated("Packs");
  }

Also, there seems to be an inconsistency between the relatedModel 'pack' and the model associated with your collection : Pack

If it still does not work, have you tried giving your key a name that is not the same as your collectionType ?

链接地址: http://www.djcxy.com/p/65522.html

上一篇: 查看主干/骨干中的+子视图

下一篇: 关系型FetchRelated不会获取任何东西