How to add a new many relationship to parent model?
Disclaimer: I tried to make a jsfiddle of this, but without a public source for the RESTAdapter, I couldn't really make it work.
I have a model with a hasMany array of child models. I need to add a new model to this child array and save to the server:
App.FooModel = DS.Model.extend({
'name': DS.attr('string'),
'bars': DS.hasMany('App.BarModel')
});
App.BarModel = DS.Model.extend({
'name': DS.attr('string'),
});
App.ApplicationController = Ember.Controller.extend({
init: function() {
var foo = App.FooModel.find(101); // -- currently has bars[201, 202, 203]
var newBar = loadFixture( App.BarModel, 204 );
var self = this;
setTimeout( function() { // -- just to be sure our models are loaded before we try this
// foo.currentState: saved
foo.get('bars').addObject(newBar);
// foo.currentState: saved
foo.store.commit(); // -- nothing happens
}, 1000);
}
});
App = Ember.Application.create({
store: DS.Store.create({
revision: 11
})
});
But nothing happens. My parent model doesn't get marked as dirty, so the store never attempts a commit. Is there a different way I should be adding this relationship to the parent? Is this a bug?
Current Workaround:
foo.get('bars').addObject(newBar);
var save = foo.get('name');
foo.set('name', (save + '!'));
foo.set('name', save); // -- this marks our record as dirty, so a save will actually happen
foo.store.commit();
Edit 1: I'm aware that ember-data will only serialize this data if it was embedded to begin with (https://stackoverflow.com/a/15145803/84762), but I have overridden my serializer to handle this. The issue I'm having is that the store never even attempts to save this change so we never even get to the serializer.
Edit 2: I suspect this might have something to do with this bug, but at the same that would mean this wouldn't work for anyone and I have a hard time believing no one else has run into this, yet.
It looks like you're Modeling a one to many relationship yet you didn't include the belongsTo
option on App.BarModel
. Check this link out:
http://emberjs.com/guides/models/defining-models/#toc_one-to-many
App.Post = DS.Model.extend({
comments: DS.hasMany('App.Comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('App.Post')
});
For what I understand, you did not use the embedded
feature of relationship but overrided your serializer to handle the serialization of bars
objects into foo
object.
I think your bug probably came from here : if your relation is not embedded there is no reason to mark the foo
object dirty as when you add an object to his bars
association what should change is usually a key foo_id
of the bar
object you added, then there is no changes of the foo
object to send to the API.
上一篇: Ember.js数据冲突解决/冲突失败
下一篇: 如何添加一个新的关系到父模型?