Search code examples
javascriptember.jsember-data

Ember data difference between find() and getById()


I know that there is a question named : Ember data: what is difference between find and findById?. However, correct if I'm wrong, but I think that it relates to an older version of Ember data since I can't find this method in the embet-data doc.

I was trying to insert a new category in my catalog. This wouldn't work:

newRecord: function() {
    catalog = this.store.find('catalog', 1);
    record = this.store.createRecord( 'category', {category_name_fr_sh: 'Nouvelle categorie'});
    catalog.get('catalog_categories_ids').pushObject(record);
    this.set('content', record);
},

But this work :

newRecord: function() {
    catalog = this.store.getById('catalog', 1);
    record = this.store.createRecord( 'category', {category_name_fr_sh: 'Nouvelle categorie'});
    catalog.get('catalog_categories_ids').pushObject(record);
    this.set('content', record);
},

The doc says

Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it's available. Otherwise, it will return null.

I really don't understand why "trggering the fetch" wouldn't work. I tought that the find() first look if it's in the store cache and only fetch if it doesn't find it. Can someone enlighten me?


Solution

  • this.store.find('catalog', 1); doesn't return the record, it return a DS.PromiseObject. Because, if your record is not present in the record cache, a request to the server is needed. If the record is already loaded, you still have the promise object, to keep the same method behavior, but no request is sent to the server.

    this.store.getById('catalog', 1); return the object from the record cache if present. Probably this work because you already loaded the catalogs using this.store.find('catalog'); or this.store.find('catalog', 1);

    You can get the catalog record from DS.PromiseObject using then method:

    newRecord: function() {
        var self = this;
        var catalogPromise = this.store.find('catalog', 1);
        catalogPromise.then(function(catalog) {
            var record = this.store.createRecord( 'category', {category_name_fr_sh: 'Nouvelle categorie'});
            catalog.get('catalog_categories_ids').pushObject(record);
            self.set('content', record);
        })
    },