emberjs/data — Issue #101: ER: Inverse Relationships should be updatable from adapter
Author: pixelcort
Created: 2012-02-16 21:45:24+00:00
State: open

I have a one-to-many relationship in two of my models, and I want the hasMany property on one of them to update when the adapter loads new instances of the other one.

For example:

App.Deck = DS.Model.extend({
name: DS.attr('string'),
cards: DS.hasMany('App.Card')
});

App.Card = DS.Model.extend({
question: DS.attr('string'),
answer: DS.attr('string'),
deck: DS.hasOne('App.Deck')
});

Let's say I have two decks and five cards per deck loaded already. Then let's say my adapter loads an eleventh new card in which has a deck key on its hash pointing to one of the existing decks.

Currently, the cards property on the relevant deck does not update.

Instead, the deck that the new card should have its cards property updated to include the new card.

The workaround I'm currently using is to define the cards property as follows:

App.Deck = DS.Model.extend({
name: DS.attr('string'),
cards: function() {
return App.store.filter(App.Card, function(hash) {
return false; // We don't know the id for this deck yet
});
}.property().cacheable(),
isLoadedOrIdDidChange: function() {
var id = this.get('id');
if (!id) return;
if (this._cardFilterFunctionWasSet) return;
this.setPath('cards.filterFunction', function(hash) {
return hash.deck === id;
});
this._cardFilterFunctionWasSet = true;
}.observes('isLoaded','id'),
});

However, this creates an O(n) performance issue, since each new card has to be run through every deck's filter for cards. When I get up to 10-20 decks and hundreds of cards coming in I can run into O(n*m) performance here.