Skip to content

Instantly share code, notes, and snippets.

@alexspeller
Last active August 29, 2015 14:00
Show Gist options
  • Save alexspeller/5d674368c067e34daf87 to your computer and use it in GitHub Desktop.
Save alexspeller/5d674368c067e34daf87 to your computer and use it in GitHub Desktop.
# This won't be live if bars is a hasMany relationship
foo.get 'bars'
# Instead do this and use the patch below to get a live array:
hasManyHack foo, 'bars'
# workaround for https://github.com/emberjs/data/issues/1308 -
# once the SSOT branch is merged this should be able to be replaced
# with parentRecord.get(collectionName).
# In short, the problem is that if you have an async hasMany relation,
# the collection is not live and is not updated if records are added
# or deleted. This workaround can be used in model hooks to use a live
# collection that is requested from the server the first time it's
# accessed
window.hasManyHack = (parentRecord, collectionName) ->
parentId = parentRecord.get 'id'
relationships = Em.get parentRecord.constructor, 'relationshipsByName'
relationship = relationships.get collectionName
idPath = parentRecord.constructor.typeKey + '.id'
parentRecord.get(collectionName).then ->
parentRecord.store.filter relationship.type, (record) ->
record.get(idPath) is parentId
@knownasilya
Copy link

Here's a JS version:

foo.get('bars');

hasManyHack(foo, 'bars');

window.hasManyHack = function(parentRecord, collectionName) {
  var parentId = parentRecord.get('id');
  var relationships = Em.get(parentRecord.constructor, 'relationshipsByName');
  var relationship = relationships.get(collectionName);
  var idPath = parentRecord.constructor.typeKey + '.id';

  return parentRecord.get(collectionName).then(function() {
    return parentRecord.store.filter(relationship.type, function(record) {
      return record.get(idPath) === parentId;
    });
  });
};

@knownasilya
Copy link

Still can't save the changes:

hasManyHack(foo, 'bars').then(function (bars) {
  bars.removeObjects(bars).addObjects(newBars);
  //foo.get('bars') === bars
  foo.save().then(function () {
    // save PUTs the array of id's for bars and not newBars..
  })
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment