Ember data saving a relationship

前端 未结 2 1043
野趣味
野趣味 2020-12-01 08:26

I\'m having difficult saving a one-to-many relationship in ember data. I have a relationship like this:

App.ParameterSet = DS.Model
    name: DS.attr(\"strin         


        
2条回答
  •  甜味超标
    2020-12-01 09:20

    The serialization of hasMany relationships is handled by the addHasMany() method of json_serializer.js.

    The following note is included in the source code:

    The default REST semantics are to only add a has-many relationship if it is embedded. If the relationship was initially loaded by ID, we assume that that was done as a performance optimization, and that changes to the has-many should be saved as foreign key changes on the child's belongs-to relationship.

    To achieve what you want, one option is to indicate that the relationship should be embedded in your adapter.

    App.Store = DS.Store.extend({
      adapter: DS.RESTAdapter.extend({
        serializer: DS.RESTSerializer.extend({
          init: function() {
            this._super();
            this.map('App.ParameterSet', {
              regions: { embedded: 'always' }
            });
          }
        })
      })
    });
    

    Of course now your back-end will need to actually embed the associated regions' JSON within the parameter set's JSON. If you want to keep things as they are, you can simply override addHasMany() with custom serialization.

    App.Store = DS.Store.extend({
      adapter: DS.RESTAdapter.extend({
        serializer: DS.RESTSerializer.extend({
          addHasMany: function(hash, record, key, relationship) {
            // custom ...
          }
        })
      })
    });
    

提交回复
热议问题