简体   繁体   中英

Using Rails Serializers (active_model_serializers) to render key/value pairs based on incremental primary keys

I'm trying to format the serialized output from the active_model_serializers gem as key/value pairs.

By default, ActiveModel::Serializer renders an output like this:

[
  {
    "id": 1,
    "value": "foo"
  },
  {
    "id": 2,
    "value": "bar"
  }
]

I'm looking to format the output like this:

{
  1: {
    "value": "foo"
  },
  2: {
    "value": "bar"
  }
}

Is this possible using active_model_serializers?

It seems that active_model_serializer is following 1.0 of the format specified in jsonapi.org/format . I don't think you can do something like that, maybe you can try jbuilder or rabl

PS: Actually I have this problem, too. I can't figure it out by using active_model_serializer, If you have fixed this, please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM