dhruvaray/backbone-associations

Relational sibling references

Closed this issue · 0 comments

Given this structure, is it possible for the referenced fruit models on Salads (within the contains container) to be references to the fruits themselves?

var data = {
  fruit: [
    {
      id: 1,
      name: "Banana"
    },
    {
      id: 2,
      name: "Apple"
    }
  ]
  salads: [
    {
      name: "Everything",
      contains: [
        { id: 1 },
        { id: 2 }
      ]
    },
    {
      name: "Waldorf Salad",
      contains: [
        { id: 2 }
      ]
    }
  ]
}

I may be thinking of the problem incorrectly, but so far I've been unable to create a nice relational model. Let's start with a simple association definition:

var Fruit = Backbone.AssociatedModel.extend({

});

var Salad = Backbone.AssociatedModel.extend({
  relations: [
    type: Backbone.Many,
    key: "contains",
    relatedModel: Fruit
  ]
});

var Food = Backbone.AssociatedModel.extend({
  relations: [
    {
      type: Backbone.One,
      key: "fruit",
      relatedModel: Fruit
    },
    {
      type: Backbone.One,
      key: "salads",
      relatedModel: Salad
    }
  ]
});

var food = new Food(data);

In this scenario, food.get("fruit").get("1").get("name") will return Banana, as expected. However, food.get("salads").at(0).get("contains").at(0).get("name") will be undefined. While the type of contains is a 1:M relation to Fruit, rather than referencing a Fruit with an ID of 1, it merely attempts to create a new Fruit on Salad with an ID of 1, which doesn't include a name value.

Another attempt is to create the fruit prior to creating the salad (rather than using food at all), then using the map function to return a reference to the Fruit’s exact model:

map: function(id) {
  return fruit.get(“id”);
}

While this function returns the correct Model, Backbone.Associations does…something…which results in thinking Salads’ list of fruits contains only a single item, regardless of how many items it contains. Most all fruits are therefore dropped on the floor. Personally, the use of the map function remains unclear to me.

There are a couple keystones to getting this working correctly:

  • The implementation must support both initial import of the JSON structure and adding items post initialization with salad.get(“contains”).add(…)
  • Salad should contain references to Fruits. Modifying a fruit in either the Fruit or Salad container should bubble up an event to both containers

Is this possible with Backbone Associations?