简体   繁体   中英

How to describe hasMany relation using links in Ember.js?

I created model Consultation:

import DS from 'ember-data';

export default DS.Model.extend({
    title: DS.attr('string'),
    records: DS.hasMany('record', { async: true }),
    currentUser: DS.belongsTo('user'),
    remoteUser: DS.belongsTo('user')
});

And also I created model Record:

import DS from 'ember-data';

export default DS.Model.extend({
    record_text: DS.attr('string'),
    record_poster_id: DS.attr('string'),
    record_consultation_id : DS.attr('number'),
    consultation: DS.belongsTo('consultation'),
    isMine: DS.attr('boolean')
});

At first all consultations load during opening page. And I don't want to load all records of each consultation during opening page. To do this I added async: true but all records loaded simultaneously sending many requests like /consultations/:id/records. After that consultation and records still non-joined. I have next json response for consultation:

{  
   "consultations":[  
      {  
         "id":140721,
         "title":"ExpertId: 41217, clientId: 0",
         "links":{  
            "records":"records"
         },
         "currentUser":41217,
         "remoteUser":159984
      },
   ......
   ]
}

And for records:

{  
   "records":[  
      {  
         "record_id":681952,
         "record_consultation_id":140721,
         "record_poster_id":0,
         "record_text":"1",
      },
  ........
   ]
}

I think I need to override default serializer. I tried to create serializer for Record:

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
    primaryKey: 'record_id',
    keyForRelationship: function(key, kind) {
        return 'record_consultation_id';
    }
});

But it still doesn't work. Please advise how to join models using links?

UPDATE: Template

{{#each item in model.records}}
<div class="table message">
            {{item.record_text}}
</div>
{{/each}}

I am doing Async (lazy loading) of data using RESTAdaptor and Ember-Data too.

For my links area, i put in the full request URL as follows:

"links":{  
            "records":"/consultations/140721/records"
 },

And using firebug to look at when the request gets sent off, its only when I request for the async content that the AJAX gets fired off.

model.get('records');

Can you provide your Controllers & Template code so I can see how your accessing the Records?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM