I upgraded activemodel serializer and now the output is different than what it once was. I'm trying to get the JSON output to match what it previously was. Specifically, I'd like an objects nested attributes to be on the same level as the main object.
For example, let's say my serializer is as follows:
class DishesSerializer < ActiveModel::Serializer
has_many :ingredients
end
This would be the current output:
{
"dish": {
"dish_stuff_1": "dish_stuff_1",
"dish_stuff_2": "dish_stuff_2",
"dish_stuff_3": "dish_stuff_3",
"ingredients": {
"ingredients_stuff_1": "ingredients_stuff_1"
}
}
}
And what I'd like is something like this:
{
"dish": {
"dish_stuff_1": "dish_stuff_1",
"dish_stuff_2": "dish_stuff_2",
"dish_stuff_3": "dish_stuff_3"
}
"ingredients": {
"ingredients_stuff_1": "ingredients_stuff_1"
}
}
I am currently doing this in the controller using multiple serializers, but it takes some additional querying and feels wrong. I feel like there should be some hacky way to do it in AMS. I tried something like this:
def attributes
hash = super
hash.merge!(:dishes => dishes)
end
but that ends up in the same layer.
Any help would be greatly appreciated.
In this case, can't you just create a new serializer that has all the data you need - say a menu serializer:
class MenuSerializer < ActiveModel::Serializer
has_one :dish
has_many :ingredients
end
Not sure having a serializer that returns 2 root elements is a good idea, as that would make it hard to reuse in the future.
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.