0

These are the path url's that my server has:

GET /watchlists
GET /watchlists/:id
POST /watchlists // Create a new watchlists
PUT /watchlists/:id // Change attributes of watchlists (Like name)
POST /watchlists/:id/movies // Add a movie
DELETE /watchlists/:id/movies/:trackId //  Delete a movie by the trackid
DELETE /watchlists/:id // Delete the watchlists by is ID

Here is my model:

var WatchlistModel = Backbone.Model.extend({
    urlRoot: '/watchlists',
});

I want to know how to do the 'add a movie' with this url:

/watchlists/:id/movies 

and the delete call:

/watchlists/:id/movies/:trackId

What are the best pratices for that?

Noam Hacker
  • 4,671
  • 7
  • 34
  • 55

1 Answers1

1

One solution would be to create a Movies collection as a child of each WatchlistModel model, give it a reference of its parent and use that reference to build its url.

Assuming the reference to the parent is stored in a watchlist attribute, something like

var Movies = Backbone.Collection.extend({
    url: function() {
       return _.result(this.watchlist, 'url') + '/movies';
    }
});

var WatchlistModel = Backbone.Model.extend({
    urlRoot: '/watchlists',
    initialize: function() {
        this.movies = new Movies();
        this.movies.watchlist = this;
    }
});

You would create a new movie like this:

var lst = new WatchlistModel({id: 1});
var newmovie = lst.movies.create();
nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • 1
    shouldn't be return _.result(this.watchlist, 'url') + '/movies' ? otherwise you get the same url as the parent collection – ejosafat Mar 08 '16 at 17:34