Nocturn
Nocturn

Reputation: 321

Backbone - sync doesn't detect my collection url

I have an albums and songs relationship. In the new album view I'm asking for the songs at the same time, I'm trying to save the album model first and then save the song collection and attach it to the album.

My song collection definition:

define(function(require){
   var Song = require('models/songModel');

   Songs = Backbone.Collection.extend({
     url: 'songs/',         
     model: Song,           
   });

   return Songs;
});

I create my song collection like this:

this.songCollection = new Songs();
//In some other view that saves the songs files and returns a hash
that.songCollection.add({title:file.name,song_file:response['file_hash']});

Then I save my album model and in success try to save the songs collection adding the new album pk to all the models in the song collection:

that = this;
this.model.save(null,{                                 
    success: function(model,response){
       that.songCollection.each(function(song){                                                                                                     
          song.set('album',model.get('id'));
       });
       that.songCollection.sync('create');                                    
    },               
    error: function(response){                         
       console.log(response);                         
    }
 });

However it returns a A 'url' property or function must be specified, but I do have it specified as you can see previously. I also tried to log it before the sync call and it returns the url properly. I'm I missing something in the process? Or I can't create all those new songs in my server at once like this?

Upvotes: 0

Views: 896

Answers (1)

Paul Hoenecke
Paul Hoenecke

Reputation: 5060

You need to save each song individually. sync is not meant to be called directly, and only method 'read' is meant to work with a collection. sync('read') is called during collection.fetch().

that = this;
this.model.save(null,{                                 
    success: function(model,response){
       that.songCollection.each(function(song){                                                                                                     
          song.save({album: model.get('id')});
       });                                   
    },               
    error: function(response){                         
       console.log(response);                         
    }
 });

Upvotes: 2

Related Questions