0
votes

ember-cli 1.13.8

ember-data 1.13.11

ActiveModelAdapter

I have two objects: posts and users. I have an action on an individual post page that let users watch/follow the post.

//post model js
watchedUsers: DS.hasMany('user', { inverse: 'watchedPosts', async: true });

//user model js
watchedPosts: DS.hasMany('post', {inverse: 'watchedUsers', async: true });

//action after clicking button
action: {
    addToWatchlist(post) {
        //session.current user is declared in an initializer that lets us access the current user easily
        post.get('watchedUsers').pushObject(this.get('session.currentUser'));

        post.save().then(function() {
            console.log('post save success');
        }, function() {
            console.log('post save fail');
        }
    }
}   

In ember inspector after clicking the follow button, I see that the attribute watchedUsers for the post model update, and watchedPosts for user model update. The values disappear when I refresh. With this, I think the pushObject function itself is fine.

When looking at my PUT request to my backend to save the post model, it does not contain the json entry for the watched_user_ids. (so it is not being saved, duh) I believe this is my main problem.

I have seeded data in my rails backend that I can see/access on the ember side, so I know that the json is accessible one way. Does ember-data not support many-to-many yet? Is there something special I have to do to send/save the json for a many-to-many relationship?

1
If you look at the request body is there a watched_user array being populated with ids ? - QuantumLicht
No, everything but my many to many attribute is being sent - klementine

1 Answers

0
votes

I was able to solve this, but using a 'watchlist' object in the middle of Post and User that represented their many to many relationship. The backend/rails side it done with a many to many :through, instead of a has and belongs to many. It seems like Ember Data does not send json for HasMany attributes, which was my main problem.

Here's what the final solution looked like:

//models/user.js
export default DS.Model.extend({
     watchlists: DS.hasMany('watchlist', { async: true })
});

//models/post.js
export default DS.Model.extend({
     watchlists: DS.hasMany('watchlist', { async: true })
});

//models/watchlists.js
export default DS.Model.extend({
    user: DS.belongsTo('user', { async: true }),
    listing: DS.belongsTo('listing', { async: true }),
});

//action in a route.js
actions: {
    addToWatchlist(post) { //component sends the specific post using sendAction
        var newWatchlist = this.store.createRecord('watchlist', {
            user: this.get('session.currentUser'), //current user stored in session object
            post: post
        });
        newWatchlist.save();
    }
}