0

I am using composite primary keys in my Ruby On Rails API server. I am also using Active Model Serializers to manage the serialization of my models. I would like to use the embed: :ids feature in my serializer to embed my IDs. This works with composite primary keys, but only gives the ID's values. Since there are multiple IDs for a single record, there is no way to know which value belongs to which column.

My Serializer

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, :body
  has_many :comments, embed :ids
end

Resulting JSON

{
  "post": {
    "id": 1,
    "title": "New post",
    "body": "A body!",
    "comment_ids": [ [1, "v1"], [1, "v2"], [2, "v1"] ]
  }
}
lightswitch05
  • 9,058
  • 7
  • 52
  • 75

1 Answers1

0

I was able to work around this issue using Active Model Serilizer's embed_key option along with Composite Primary Key's ids_hash method.

My Serializer

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, :body
  has_many :comments, embed :ids, embed_keys: :ids_hash
end

Resulting JSON

{
  "post": {
    "id": 1,
    "title": "New post",
    "body": "A body!",
    "comment_ids": [
      {"comment_id": 1, "version_id": "v1"},
      {"comment_id": 1, "version_id": "v2"},
      {"comment_id": 2, "version_id": "v1"},
    ]
  }
}
lightswitch05
  • 9,058
  • 7
  • 52
  • 75