1
votes

I'm seeing some odd behavior with some custom serializer code that I wrote.

I have a field in an Asset model called 'marketName'. My Rails backend expects this field to be called 'market_name'. I've extended the ActiveModelSerializer and have overridden the 'extractSingle' and 'serialize' methods.

The odd thing is this - for all the other fields in my Asset model that are not made up of multiple words - the serialization code that I've written works great. No issues. However - for any field containing multiple words - the serialization doesn't work completely, in that while it saves the Asset when created - it doesn't correctly populate the Asset model's 'marketName' field (and any other field that is made up of multiple words).

For example if I examine the 'marketName' field in the data inspector it appears as '{}'. If I change the name of any multi word field in my Asset model to be singular (aka change 'marketName' to 'name') and update the serialization code accordingly - everthing works great.

Any idea what's going on ?

Thanks Dave

1
Sharing your serializer and some of the other relevant code would be a big helpDhaulagiri
You should handle multi word property names in your serialize and extractSingle methods. Generally speaking, you shouldn't override these methods.Pooyan Khosravi

1 Answers

0
votes

In the test of extractSingle() that the core team (see line 126, also show below incase link goes bad for future readers) did, they pass in the variables as super_villains, then later the normalize() included in ActiveModelSerializer changes it for them to superVillains.

So I think in your extractSingle assume the values are not yet camelCase, but still are still in underscore_format (e.g., "market_name"), and you should be golden!

test("extractSingle", function() {
  env.container.register('adapter:superVillain', DS.ActiveModelAdapter);

  var json_hash = {
    home_planet:   {id: "1", name: "Umber", super_villain_ids: [1]},
    super_villains:  [{
      id: "1",
      first_name: "Tom",
      last_name: "Dale",
      home_planet_id: "1"
    }]
  };

  var json = env.amsSerializer.extractSingle(env.store, HomePlanet, json_hash);

  deepEqual(json, {
    "id": "1",
    "name": "Umber",
    "superVillains": [1]
  });

  env.store.find("superVillain", 1).then(async(function(minion){
    equal(minion.get('firstName'), "Tom");
  }));
});