Search code examples
ember.jsember-data

Ember Data: Loading comments for a post from separate endpoint


I have two endpoints of interest: /posts -> to get all the posts /posts/{post_id}/comments -> to get all the comments for a post

I would like to have a comments attribute on the post model, populated with comments from the comments endpoint. How can I load comments into the posts?

I am using DS.JSONSerializer.

Thanks!


Solution

  • Give your model a hasMany property:

    import Model from 'ember-data/model';
    import { hasMany } from 'ember-data/relationships';
    
    export default Model.extend({
        comments: hasMany('comment');
    });
    

    And set in your Post payload the comments relation as a related link:

    data: {
        attributes: {}
        id: 'your-post-id',
        relationships: {
            comments: {
                links: {
                    related: 'posts/your-post-id/comments'
                }
            }
        }
    }
    

    As soon as you target the comments, Ember Data will do a call to your related link. E.g:

    {{#each post.comments as |comment|}}
        {{comment.propertyX}}
    {{/each}}