vendredi 30 janvier 2015

With Ember Data, is it possible to save many belongs_to relations in the same request independently of the RESTAdapter or the FixtureAdapter?

I have two models with a belongs_to relation.



App.Organization = DS.Model.extend({
name: DS.attr('string'),
projects: DS.hasMany('project', { async: true })
});

Zest.Project = DS.Model.extend({
name: DS.attr('string'),
organization: DS.belongsTo('organization', {async: true, inverse: 'projects'})
});


In a controller, I have already many projects and I want to create an organization and bind it to the projects:



var self = this,
newOrganization = this.store.createRecord('organization', {name: 'My pretty organization name'});

myProjects.forEach(function (project) {
newOrganization.get('projects').pushObject(project);
});

newOrganization.save().then(
function (organization) {
self.transitionToRoute(..., ...);
},
function (reason) {
self.set('error', ...);
}
);


In production I work with Rails and the RESTAdapter. As I prefer have only one request to save the organization (and not to do many save on all the projects), I update the serializer like that:



App.OrganizationSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
// thanks EmbeddedRecordsMixin!
projects: {serialize: 'ids', deserialize: 'ids'}
}
});


On the server, when it receives the request, it create the organization and update the projects. It's works!


I was happy BUT I had problems when I tried to test my code with FIXTURES. Indeed I noticed that after the success of newOrganization.save(), the project fixtures are not updated. If I want they are updated, I have to call the save function on all the projects like that:



newOrganization.save().then(
function (organization) {
organization.get('projects').forEach(function (p) {
p.save();
});
self.transitionToRoute(..., ...);
},
function (reason) {
self.set('error', ...);
}
);


But I don't want to do that in production because each 'save' triggers a request that I don't need


So is it possible to configure the FixtureAdapter for it saves the projects of an organization while it saves this organization ? Or should I use a better manner to save these belongs_to links ?





Aucun commentaire:

Enregistrer un commentaire