Add belongsTo ID attribute to payload on create/update


#1

Is there a way to add a models belongsTo id attribute to the payload when creating/updating the model? I am using JSONAPISerializer ATM but can’t find anything on the webs about how to accomplish this. Here’s an example:

Category = DS.Model.extend({});

Thing = DS.Model.extend({
  name: DS.attr(),
  category: DS.belongsTo('category')
});

// Route
thing = this.get('store').createRecord('thing', {
  name: 'Bananas',
  category: getPreviouslySaved()
});

thing.save(); // category_id is missing from the create payload

Where or how do I add category_id to the payload?


#2

I think you want to separate your create and update actions here. Take a look at the Ember guides here.


#3

Actually, I solved it with this:

export default DS.JSONAPISerializer.extend(DS.EmbeddedRecordsMixin, {
  //...

  serialize() {
    const json = this._super(...arguments);
    let atts = Ember.$.extend({}, json.data.attributes);

    if (json.data.hasOwnProperty('relationships')) {
      for (var key in json.data.relationships) {
        let relationship = json.data.relationships[key];
        if (!Ember.isArray(relationship.data)) {
          let name = Ember.String.underscore(`${key}_id`);
          atts[name] = relationship.data.id;
        }
      }
    }

    return atts;
  }

 //...
});

Just wanted to the {belongsTo}_id serialized alongside the other attributes.