Saving a hasMany relationship with JSONAPI

I’ve been trying to figure this out for a few hours now and it’s driving me crazy!

I simply want to allow Users to follow other Users. My User model looks like this;

export default Model.extend({
    name: attr('string'),
    username: attr('string'),
    avatar: belongsTo('image'),
    usersFollowing: hasMany('user')
});

When I get to creating a follow, I’ve tried this;

this.get('session.currentUser').get('usersFollowing').pushObject(userToFollow);
this.get('session.currentUser').save();

But that sends down my entire usersFollowing array to the server. This won’t be scalable. According to the JSONAPI spec, Ember Data should be making a POST request to the /users-following relationship link with just the data of the new follow.

Can anyone help with this? It seems like such a simple thing that I can’t get to work :frowning:

1 Like

From your posting I can only guess you left a lot out. So, here’s a link that may help you best: Relationships - Models - Ember Guides , good luck.

No, I’ve not left a lot out. I’ve read the guides, read the API, can’t find an answer to this.

If you want to add to a hasMany relationship, Ember is sending the entire children list to the server in a PATCH request. So for instance, say you’re adding a comment to a post that has thousands of comments, you’re going to be sending a payload with thousands of record objects (which will probably exceed HTTP limits).

I found a GitHub issue that seems to match this problem, but it’s had no updates in over 9 months.

1 Like

I think you should first add inverse parent-child relationship on User model. You defined that User has many Users via usersFollowing, but there is no belongsTo defined on User model to refer to foreign key.

export default Model.extend({
    name: attr('string'),
    username: attr('string'),
    avatar: belongsTo('image'),
    followee: belongsTo('user'),
    followers: hasMany('user', { inverse: 'followee' })
});

Also, not sure what api backend you’re using, but if it’s Rails, then you need to define two has_many through relationship with join table on same model with two foreign keys pointing to that model.