BACKBONE.JS RESTFUL URL CALLS IN RAILS

Just some notes written down for my own reference. Enjoy them if you wish!

var BookModel = Backbone.Model.extend({
  urlRoot: '/books'
});

var BookCollection = Backbone.Collection.extend({
  model: BookModel,
  url: '/books'
});

 

Create (POST)

var brandNewBook = new BookModel({ title: '1984', author: 'George Orwel' });
brandNewBook.save();

Backbone sees I'm trying to create a new book and makes the following POST request received by the Rails router:

POST /books HTTP/1.1
Host: example.com

{"title":"1984","author":"George Orwel"}

 

Read (GET) -- collection

BookCollection().fetch();

Backbone sees I'm trying to read a collection of books and makes the following GET request received by the Rails router:

GET /books HTTP/1.1
Host: example.com

 

Read (GET) -- object

new BookModel({ id: 42 }).fetch();

Backbone sees I'm trying to read a single book and makes the following GET request received by the Rails router:

GET /books/42 HTTP/1.1
Host: example.com

 

Update (PUT)

brandNewBook.set('author', 'George Orwell');
brandNewBook.save();

Backbone knows 'brandNewBook' is in the database so it updates the book with a PUT request received by the Rails router:

PUT /books/84 HTTP/1.1
Host: example.com

{"title":"1984","author":"George Orwell"}

 

Destroy (DELETE)

brandNewBook.destroy();

Backbone sees I'm trying to destroy a single book and makes the following DELETE request received by the Rails router:

DELETE /books/84 HTTP/1.1
Host: example.com

Written on October 8, 2013