adopted-ember-addons / ember-data-model-fragments

Ember Data addon to support nested JSON documents
MIT License
370 stars 114 forks source link

Issues using the ember data fragments while trying to load child data fragments on demand. #22

Closed user9821 closed 10 years ago

user9821 commented 10 years ago

I am working on a use case something like this :

var Contact = DS.Model.extend({
 firstName: DS.attr('string'),
  lastName: DS.attr('string'),
  addresses : DS.hasManyFragments('address'),
  phones : DS.hasManyFragments('phone'),
  interactions : DS.hasManyFragments('interaction')
 });

Contact can have one or more addresses , phones and interactions. However my use case restricts me from load the whole contact record at one ago.

what i am trying to do is load addresses , phones and interaction on demand. So initially only the contact record with firstname and lastname gets loaded.

I make an call from my Contact controller like : return this.store.find('contact',1); which returns me {"contacts":{"id":1,"firstName":"Joe","lastName":"Smith"}}.

Now later i want to get all the addresses related to contacts/1. var addresses = this.store.find('address',{contactId:1}); I get a json response

{"addresses":[{"id":"200","street":"6262 Sunset Drive","city":"Miami","state":"Zip"}]}

as soon as it gets this response back in controller the application errors out.

I get this error in the logs:

  Error: Assertion Failed: Error: Assertion Failed: `interval-intl-ember-clii@model:address:` does not appear to be an ember-data model.

My question is it possible to use data Fragments to get child objects on demand and attach to the parent object or do i have to get the whole contact object at one go (which i am reluctant to do as i might impact performance )

I am using data fragments as persistence of the child objects is managed completely through the parent object

chrisvariety commented 10 years ago

If your addresses have IDs, you're better off using a real Ember Data model and not fragments at all. For persistence, you can override the model's serializer to inline whatever data you'd like, e.g.

export default DS.RESTSerializer.extend({
  serialize: function(user) {
    var serialization = this._super(user);

    serialization.addresses = Ember.get(user, 'addresses').map(function(address) {
      return address.serialize();
    });

    return serialization;
  }
});
slindberg commented 10 years ago

@chrisvariety is correct: if you are embedding full-fledged records with unique identifiers, you definitely want to be using a custom serializer, most likely one that makes use of DS.EmbeddedRecordsMixin.

If, as I suspect, you are after the dependent relationship dirty state tracking that Model Fragments offer, you might take a look at this experimental plugin (keep in mind that it is very intrusive solution and may not be compatible with future versions of Ember Data).