dgsan
dgsan

Reputation: 285

How do I customize the id of a json-api serialized model with active model serializers?

I'd like to be able to customize the id used with the json api adapter in active model serializers.

Namely, I have a project where the actual ruby-on-rails IDs for a particular model being serialized aren't considered public-facing for various reasons, but an alternate public-facing unique identifier is available.

I'd like to use this identifier as the id for the json api serialized content, but I have been unable to figure out any obvious way to override IDs within the json api serializer.

Basically, given models [{ id: 1, alt_id: '2aef7e'}, { id: 2, alt_id: '3b47c0' } ...] I'd like a way to create a serialized version:

{
 "data":
  [{
    "id" : "2aef7e",
    "type" : "my-model",
    "attributes" : {...},
    "relationships" : {...}
   },{
    "id" : "3b47c0",
    "type" : "my-model",
    "attributes" : {...},
    "relationships" : {...}
   }],
 "included" : [ ... ]
}

instead of:

{
 "data":
  [{
    "id" : "1",
    "type" : "my-model",
    "attributes" : {...},
    "relationships" : {...}
   },{
    "id" : "2",
    "type" : "my-model",
    "attributes" : {...},
    "relationships" : {...}
   }],
 "included" : [ ... ]
}

but have been unable to find an obvious means of overriding the ID value for serialization.

Upvotes: 1

Views: 1908

Answers (1)

fedebns
fedebns

Reputation: 494

You can define a method within the serializer to avoid using object's method.

class MySerializer < ActiveModel::Serializer
  attribute :id
  def id
    object.alt_id
  end
end

Upvotes: 2

Related Questions