Currently, I need to implement many-to-many relationship between "section" and "fields" through intermediate table "field-sections". So, I have setup the model and serializer as below. (I do not have separate api for intermediate table and am using embedded records to pass the fieldSections)
//Section Model
export default DS.Model.extend({
name: DS.attr(),
template: DS.belongsTo('template'),
fields: DS.hasMany('field'),
fieldSections: DS.hasMany('fieldSection')
});
//FieldSection Model
export default DS.Model.extend({
section: DS.belongsTo('section'),
field: DS.belongsTo('field'), //Fields hasMany fieldSections
fieldOrder: DS.attr('number')
});
//Section serializer
export default ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin,{
attrs: {
fieldSections: {
embedded: 'always',
serialize: 'records',
deserialize: 'ids'
}
},
keyForAttribute(attr) {
if(attr == "fieldSections") {
return "field_sections_attributes";
}
else {
return this._super(attr);
}
}
});
To update the "field-sections", in the backend I am clearing the existing relationships and creating new ones according to the request.
def section_params
params.require(:section).permit(:name, :template_id, field_ids: [], field_sections_attributes: [:field_order, :field_id])
end
def update
@section.field_sections.destroy_all unless params[:section][:field_sections]
@section.update(section_params)
respond_with @section, status: :ok
end
While doing this, the ids for the fieldSections are changed to a new value (since it is clearing all the previous ones and creating new one entirely). These new ids are returned to the client side.
Now problem is that, ember-data does not remove the old ids and just appends the new ids to the relationship. Thus, in the section model there data with old and new ids both and the objects are repeated.
This setup is working correctly while creating and loading the records but while updating the intermediate records are not update properly.
For eg: Initially before update, If a section had fieldSections with ids "1,2,3" the rails updates them to "4,5,6" and returns it in the section object. Now, "ember-data" does not clear the "1,2,3" and just appends it resulting in "1,2,3,4,5,6".
Please suggest regarding how this problem can be solved.
Aucun commentaire:
Enregistrer un commentaire