Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EmberJS - record with hasMany relation fails to load

I am using EmberJS 1.0.0 with Ember Data 1.0.0 beta and the latest version of the LocalStorage Adapter. When I try to load a record with a hasMany relationship from the store I get the follwing error:

ember-1.0.0.js (Line 394)

Assertion failed: You looked up the 'items' relationship on 'App.List:ember236:1' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (DS.attr({ async: true }))

and ember-data.js (Line 2530)

TypeError: resolver is undefined }).then(resolver.resolve, resolver.reject);

Quick demo app: http://jsbin.com/oKuPev/49 (watch the console)

<script type="text/x-handlebars">      
    List: {{name}}       
    <div>    
        {{#each items}}
            {{id}} - {{name}}<br/>
        {{/each}}
    </div>
</script>

<script type="text/javascript">

    window.App = Ember.Application.create({});        
    App.ApplicationAdapter = DS.LSAdapter.extend({});

    var FIXTURES = {
      'App.List': {
        records: {
          '1': { id: '1', name: 'The List', items: ['1','2'] }
        }
      },
      'App.Item': {
        records: {
          '1': { id: '1', name: 'item 1', list: '1' },
          '2': { id: '2', name: 'item 2', list: '1' }
        }
      }
    }

    // Store fixtures in localStorage
    localStorage.setItem('DS.LSAdapter', JSON.stringify(FIXTURES));

    // Models
    App.List = DS.Model.extend({
        name: DS.attr('string'),
        items: DS.hasMany('item')
    });  

    App.Item = DS.Model.extend({
        name: DS.attr('string') ,
        list: DS.belongsTo('list')
    });


    // Route  
    App.ApplicationRoute = Ember.Route.extend({    
        model: function() {
          // Fails!!!
          return this.store.find('list', 1);           
        }
    });       

  </script>      

I'm not sure if the problem is ember.js, ember-data.js or the LocalStorage adapter.

like image 503
Alex Avatar asked Sep 09 '13 19:09

Alex


2 Answers

You need to define "items" on your model as being async in nature as ember makes separate requests for those models and then joins them together asynchronously.

App.List = DS.Model.extend({
  name: DS.attr('string'),
  items: DS.hasMany('item',{async:true})
}); 
like image 162
Chuck Avatar answered Sep 20 '22 14:09

Chuck


This works if you define items as an asynchronous relationship.

item: DS.hasMany('item',{async:true})

Here's a working jsbin : http://jsbin.com/oKuPev/53/edit

like image 39
Jeremy Green Avatar answered Sep 17 '22 14:09

Jeremy Green