Belongs to relationship nulls out belongs to id on save


#1

I have a model

GroupMeasure = DS.Model.extend(
  measureId: attr()
  measure: DS.belongsTo('measure')
)

I want to save that model with just the measureId

When I save measureId is always null in the json payload.

I traced the problem to here

It sets the attributes first to the proper value and then it nulls it out because the relation is null.

    record.eachAttribute(function(key, attribute) {
      this.serializeAttribute(record, json, key, attribute);
    }, this);

    record.eachRelationship(function(key, relationship) {
      if (relationship.kind === 'belongsTo') {
        this.serializeBelongsTo(record, json, relationship);
      } else if (relationship.kind === 'hasMany') {
        this.serializeHasMany(record, json, relationship);
      }
    }, this);

Is this a bug or am I just not doing it correctly?


#2

@varblob What Serializer are you using? It sounds like you have a keyForRelationship defined somewhere that is causing your measure relationship to be serialized as measureId.


#3

@bmac I’m using DS.ActiveModelSerializer and I think you’re correct. I’ll dig down that path. Thanks for the pointer.

Ok I dug through and the responsibility lies with ActiveModelSerializer. That said ActiveModelSerializer is providing a reasonable key and this seems like a ?reasonable? use case as well. Am I using ActiveModelSerializer wrong?


#4

In case anyone else thinks of monkey patching this to work BEWARE it causes the loading of the belongs to record to get mucked up Recursive Sideloading

I really do wish I knew the correct way to accomplish this task. My current solution is to create a new record with just the ID on it and store that but it seems pretty wrong, not to mention it will probably break something else later.