I'm not familiar with the JSON response display format I got stuck so I organized it.
ActiveModelSerializer has three types of adapters (JSON display format).
attributes: Adapter set by default. Generate a json response without a root key. json: The response always has a root key and generates a json response json_api: A response is returned according to the display format established by the organization that determines the JSON specification called JSON API.
If you want to use: json and: json_api by default, go to the initializers directory Create a separate file such as active_model_serializers.rb (any name is OK) and Set the JSON display format there as follows.
# config/initializers/active_model_serializers.rb
ActiveModel::Serializer.config.adapter = :json_api
The actual response looks like this
[
{"id"=>69,
"title"=>"pot",
"updated_at"=>"2020-10-20T20:52:09.044Z",
"user"=>
{"id"=>3,
"name"=>"xu6i65h83tbvexx5dld89w39xn4u9",
"email"=>"[email protected]"}
γ}
]
"articles" is the root key. The root key name is getting the controller name.
{"articles"=>
[
{"id"=>72,
"title"=>"Oh yeah",
"updated_at"=>"2020-10-20T20:58:15.458Z",
"user"=>
{"id"=>3,
"name"=>"e8zu6a5m08jlgd3w1ddlxkoa",
"email"=>"[email protected]"}
},
]
}
{"data"=>
[
{"id"=>"66",
"type"=>"articles",
"attributes"=>{"title"=>"Hinkyaku", "updated-at"=>"2020-10-20T20:44:16.765Z"},
"relationships"=>
{"user"=>
{"data"=>
{"id"=>"3",
"type"=>"users"}
}
}
}
]
}
It feels like it's becoming more and more structured. The fact that json_api is a display format that conforms to the JSON specifications Is it the easiest to generalize?
Recommended Posts