Saving object with children in 1 request

I have previously saved an object with children in multiple requests but I don’t like the fact that if one loses internet connection in the middle of the save, the client and server are out of sync unless one does a browser refresh. I’m trying to do it in 1 one request using Rail’s accepts_nested_attributes_for. The save works but Ember Data treats the children in the response as new children i.e. if an object has 1 newly created child before the save, after the save it will have 2 - the original record and the record from the response. Has anybody figured out a way around this?

Below is how I’m adding ‘_attributes’ suffix to embedded records key. I’m using Ember Data 1.0.0 beta 16.

app/serializers/application.coffee:

ApplicationSerializer = DS.ActiveModelSerializer.extend RailsEmbeddedRecordsMixin,
  attrs:
    childItems:
      serialize: 'records'

app/serializers/rails-embedded-records-mixin.coffee:

RailsEmbeddedRecordsMixin = Ember.Mixin.create DS.EmbeddedRecordsMixin,

      serializeBelongsTo: (snapshot, json, relationship) ->
        attr = relationship.key
        if @noSerializeOptionSpecified(attr)
          @_super(snapshot, json, relationship)
          return
        includeIds = @hasSerializeIdsOption(attr)
        includeRecords = @hasSerializeRecordsOption(attr)
        embeddedSnapshot = snapshot.belongsTo(attr)
        if includeIds
          key = @keyForRelationship(attr, relationship.kind)
          if !embeddedSnapshot
            json[key] = null
          else
            json[key] = embeddedSnapshot.id
        else if includeRecords
          key = @keyForAttribute(attr) + '_attributes'
          if !embeddedSnapshot
            json[key] = null
          else
            json[key] = embeddedSnapshot.record.serialize(includeId: true)
            @removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[key])

      serializeHasMany: (snapshot, json, relationship) ->
        attr = relationship.key
        if @noSerializeOptionSpecified(attr)
          @_super(snapshot, json, relationship)

        includeIds = @hasSerializeIdsOption(attr)
        includeRecords = @hasSerializeRecordsOption(attr)
        if includeIds
          key = @keyForRelationship(attr, relationship.kind)
          json[key] = snapshot.hasMany(attr, ids: true)
        else if includeRecords
          key = @keyForAttribute(attr) + '_attributes'
          json[key] = snapshot.hasMany(attr).map (embeddedSnapshot) =>
            embeddedJson = embeddedSnapshot.record.serialize(includeId: true)
            @removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson)
            return embeddedJson

Hmm look like it was disscussed here Proposal/Fix: Saving new embedded records creates duplicates

Look like the fix on newer version of ember data.

1 Like