lundi 4 avril 2016

Loading relationship data using Ember 2

I am having some trouble loading relationship data using Ember 2.0. Given the following two models, Project and LineItem, I am trying to list all line items belonging to a given project:

export default DS.Model.extend({
    name: DS.attr(),
    organisation: DS.attr(),
    customer: DS.attr(),
    hours: DS.attr({defaultValue: 0}),
    line_items: DS.hasMany('line-item', {async: true})  
});

export default DS.Model.extend({
    name: DS.attr(),
    value: DS.attr({defaultValue: 1}),
    quantity: DS.attr({defaultValue: 1}),
    state: DS.attr({defaultValue: 'OPEN'}),
    project: DS.belongsTo('project')
});

Inside my route, I load a given project without problems:

export default Ember.Route.extend(AuthenticatedRouteMixin, {
    model(params) {
        return this.store.findRecord('project', params.project_id);
    }
});

Inside my component, I then try to load my line items as follows:

import Ember from 'ember';

export default Ember.Component.extend({
    store: Ember.inject.service(),
    lineItems: function () {
        return this.get('project').get('line_items').toArray();
    }.property('project.line_items'),
});

When I try to iterate over my line items inside my template however, nothing happens:

{{#each lineItems as |item|}}
   <tr>
     <td>
        <a href="#">{{item.name}}</a>
     </td>
   </tr>
{{/each}} 

No luck using {{#each project.line_items as |item|}} either. Printing the output of this.get('project').get('line_items').toArray() shows an empty list.

However my project contains line items, as expected:

{  
   "data":{  
      "type":"projects",
      "id":"7d93633d-a264-4cb3-918c-82cc44cb76e2",
      "attributes":{  
         "created":"2016-04-04T19:02:03.113408Z",
         "modified":"2016-04-04T19:02:03.113511Z",
         "name":"Sample name",
         "hours":0
      },
      "relationships":{  
         "line_items":{  
            "meta":{  
               "count":1
            },
            "data":[  
               {  
                  "type":"LineItem",
                  "id":"01915d73-fde5-4b6f-8915-174c16592942"
               }
            ]
         }
      }
   }
}

...my line item:

      {
            "type": "line-items",
            "id": "01915d73-fde5-4b6f-8915-174c16592942",
            "attributes": {
                "created": "2016-04-04T19:02:15.622483Z",
                "modified": "2016-04-04T19:02:15.622534Z",
                "name": "Test Line Item",
                "value": 1,
                "quantity": 1
            },
            "relationships": {
                "project": {
                    "data": {
                        "type": "projects",
                        "id": "7d93633d-a264-4cb3-918c-82cc44cb76e2"
                    }
                }
            }
        }




Aucun commentaire:

Enregistrer un commentaire