Search code examples
ruby-on-railsrubyjsonhashactive-model-serializers

Ruby On Rails - Active Model Serializer; Create a custom JSON serializer


how can I create a json with this key & value mapping?

  • The key should be the attribute 'id' of the record.
  • The value should be the attribute 'name' of the record.

i.e.

[{ "21": "Jason" },
{ "22": "Britney" },
{ "25": "Donald" },
{ "#{id}": "#{name}" }]

Is it possible to achieve this using the Active Model Serializers gem?


Solution

  • Why do you need a serializer?

    users.map{|u| { "#{id}": name }.to_json