Can't get data from hasMany relationship


#1

I try to build Rails+Ember app using Ember data.

Model:

export default DS.Model.extend({
    name: DS.attr('string'),
    content: DS.attr('string'),
    image_before: DS.attr('string'),
    created_at: DS.attr('date'),
    updated_at: DS.attr('date'),
    status: DS.attr('number'),
    comments: DS.hasMany('comment', {async: true}),
    user: DS.belongsTo('user'),
});

and get json like this (json is generated with active_model_serializers)

    {"work":{
            "id":3,  
            "user_id":1, 
            "content":"My first photo", 
            "image_before": "image_before/original/AnViWyuup5I.png", 
            "created_at":"2015-08-11T16:57:24.153Z", 
            "updated_at":"2015-11-13T11:39:44.076Z", 
            "status":1, 
            "comment_ids":[13]
    },
    "comments": [{
        "id": 13, 
        "text": "good!", 
        "created_at": "2015-09-28T10:34:16.461Z", 
        "user_id": 2
    }]
}

Template is:

<div class="work__img-wrapper">
    <img class="work__img" src="{{model.image_before}}">
</div>
<div class="work__content">{{model.content}}</div>

<div class="work__comments-list">
        <strong>Comments( {{model.comments.length}} ):</strong>
        {{#each model.comments as |comment|}}
            <div class="work__comment">
                <div class="work__comment-text">{{comment.text}}</div>
            </div>
        {{/each}}
</div>

At page, I get all information about work and Comments( 0 ), but Ember Inspector at Chrome shows comment.

How i can print comments too?


#2

Try to set your serializer for (work) to look like something like this

import DS from 'ember-data';

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
   attrs: {
      comments: {embedded: 'always' }
   }
});

If it not work, you need to compute it (alias) on your controller / component:


export default Ember.Controller.extend({
   comments: Ember.computed.alias('model.comments')
})

then use it on your template:

{{each comments key="id" as |comment|}}
   <div class="work__comment">
         <div class="work__comment-text">{{comment.text}}</div>
   </div>
{{/each}}

#3

it doesn’t work for me


#4

Problem solved. By default, DS.hasMany associated IDs are not added to the objects that are serialized (http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html).

Should add

export default DS.ActiveModelSerializer
    .extend(DS.EmbeddedRecordsMixin)
    .extend({
    attrs: {
        comments: {serialize: 'ids', deserialize: 'ids'}
    }
});