cbmeeks
cbmeeks

Reputation: 11420

How do I define nested resources for backbone.js?

So I have a Rails 3.1 app that contains nested resources:

resources :projects do
  resources :todos do
    resources :tasks
  end
end

I have defined my backbone.js models like:

var Task = Backbone.Model.extend({url:'/projects/1/todos/20/tasks'})

I can now create a new nested task as simply as:

task.set({description:"This is backbone.js created task!!!"})
task.save()

This, is pretty awesome.

However, note that I hard-coded the project/:project_id/todos/:todo_id/tasks url. Of course, I can generate this dynamically but I was wondering if there was a better way.

Thanks for any suggestions.

Upvotes: 4

Views: 3751

Answers (1)

Elf Sternberg
Elf Sternberg

Reputation: 16361

Backbone.Model.extend is used to create subclasses, not objects, so creating a new class with a static URL and then instantiating it seems to be a particularly hairy method of going about things.

For problems like this, I'm very fond of Backbone Relational, which allows you to define a parallel set of structures as classes in Backbone, and have the Project object upload itself with all of its associated ToDo and Task objects. You would only ever send Projects as the RESTful "coarse document" you send to the client and receive from the client. See The Richardson Maturity Model for a discussion of REST, because backbone fully supports this particular model.

Another way is to SOAPly send change messages as updates, but that would take some hacking and understanding of Backbone's internal sync method.

Upvotes: 5

Related Questions