3

First I apologize as I am not sure the question title accurately describes what I am trying to do. I love/hate backbones REST api structure, but I am trying add on to it a bit and support a 'graph' of relationships between the models.

So the simplest end point is something like:

/machines/:id

or

/projects

But I want to take it a step further and show the 'graph' of relationships:

/machines/:machine_id/projects

or

/machines/:machine_id/projects/:project_id

I am trying to think of the best approach to take and wonder if anyone has any experience they would care to share in this area. As it stands now I have defined models for machines and projects and the non-relational end points work. I guess my next step would be to create a fictitious composite model MachinesProjects - but not sure how I would go about hacking up the model's url concatenation to respond to the different attributes that represent ids. Further, I'm hoping there's something better as I really don't want to explicitly define a model for every arc in the graph between model types.

Matthew Ward
  • 351
  • 3
  • 12

1 Answers1

4

How about something like the following?

var Machine = Backbone.Model.extend({
  urlRoot:"/machines"
});

var Project = Backbone.Model.extend({
  urlRoot:"/projects"
});

var MachineProject = Project.extend({
  url: function() {
    return this.machine.url() + Project.prototype.url.call(this);
  },
  initialize: function(options) {
    this.machine = options.machine;
  }
});
jevakallio
  • 35,324
  • 3
  • 105
  • 112