Reputation: 9261
I've got a set of models named Profile
and Tag
. Profiles can have many tags, and tags can belong to many profiles. My models are set up like this:
App.Profile = DS.Model.extend({
name: DS.attr(),
tags: DS.hasMany('tag')
});
App.Tag = DS.Model.extend({
title: DS.attr(),
profile: DS.hasMany('profile')
});
And I wrote the following code to test the relations and submit the data to the server:
var profile = this.store.createRecord('profile', {
name: 'John Doe'
});
var tag1 = this.store.createRecord('tag', {
title: 'Tag 1'
});
var tag2 = this.store.createRecord('tag', {
title: 'Tag 2'
});
var tag3 = this.store.createRecord('tag', {
title: 'Tag 3'
});
profile.get('tags').pushObject(tag1);
profile.get('tags').pushObject(tag2);
profile.get('tags').pushObject(tag3);
profile.save();
However the relations are never sent to the server, even if I save the tags first and the profile afterwards.
No matter what the data Ember POSTs to /profiles/
always contains "tags": [ null, null, null ]
Edit: I was saving my models in the wrong way, this code works for me:
profile.get('tags').save().then(function() {
profile.save();
});
Upvotes: 1
Views: 574
Reputation: 47367
When you save profile it saves the name and the id's of the tags. Relationships aren't embedded into the json when sending up by default. It's sending up the ids of the tags, which is null. You need to save the tags first (and your server needs to return an id, generally it returns the entire model with the id). Then when you save profile the ids will be sent. If you want to just hard code a couple to see how it works just put in the id.
var tag1 = this.store.createRecord('tag', {
title: 'Tag 1',
id:21838123823
});
All that being said, you can create a custom serializer that sends everything up if you wanted to, but that's not how the default rest adapter/serializer work.
Upvotes: 1