mercredi 21 août 2019

Serialize has many only IDs when existing, but empty array when nil

Ember noob here, I've looked through docs on serialization and stack overflow posts and I either cannot find what I'm looking for or do not understand enough to know its what I'm looking for.

Currently I have an object called recipe, and recipe can have many recipes called linked recipes. When linked recipes exist, the serialization passes only the ID's into the requests to my back end, as intended. However when there are no linked recipes, nothing is serialized because there are no IDs. I would like an empty array to be passed back but it seems my serialization methods are preventing this.

    linkedRecipes: {
      serializer: 'ids',
      deserialize: 'ids'
    }

serializeHasMany: function(snapshot, json, relationship) {
  if(relationship.key == "linkedRecipes") {
    var k = "linked_recipe_ids";
    var records = snapshot.hasMany('linkedRecipes');
    var parameterValue = [];
    if(records) {
      records.forEach(function(item, index) {
        parameterValue.push(item.get('id'));
      });
    }
    json[k] = parameterValue;
  }
}

If linked recipes exist, my put request looks like linked_recipe_ids: ["1", "3"], the goal outcome is for when linked recipes dont exist, for the request to look like linked_recipe_ids: []

If there's any more code you'd like me to show I'd be happy to do so.




Aucun commentaire:

Enregistrer un commentaire