1

Longtime Rails Dev, Backbone Noob.

In my rails models, a project has many tasks and a task belongs to a project.. Standard stuff.

Trying to get a project's tasks json in a collection.

ExampleApp.Collections.Tasks = Backbone.Collection.extend({
  url: '/projects/<dynamic_id>/tasks',
  model: ExampleApp.Models.Task
});

Every example Ive seen so far references the url as /tasks. Id like to pass a project id to the collection to get that projects tasks.

Ive checked out Backbone Relational but not sure what the best solution is.

Cheers

stuartchaney
  • 432
  • 5
  • 16

2 Answers2

2

I would highly recommend using Backbone-Relational as opposed to hacking the relationship on your own. Reasons for using Backbone-Relational from personal experience:

  • Creates forward and backward relationships, so you can get all tasks related to a project, or the project to which a task belongs
  • Easy to serialize, and automatic deserizalization. That is, you give it a JSON and it builds out all the models and their relationships. Very handy.
  • Your models remain independently defined and can use standard Backbone stuff to save/fetch without any additional work.
  • It can also play nicely with various Backbone extensions such as Marionette and ioBind/ioSync.
Tony Abou-Assaleh
  • 3,000
  • 2
  • 25
  • 37
1

One approach is to define url as a function and set your project_id prior to fetch()

ExampleApp.Collections.Tasks = Backbone.Collection.extend({
    model: ExampleApp.Models.Task

    url: function() {
        return 'projects/'+this.project_id+'/tasks';
    },

    setProjectId(project_id) {
        this.project_id = project_id;
        this.fetch();
    }
});
Peter Ludlow
  • 86
  • 2
  • 5