I have two associated models, the parent= Activity
, and it has_many association to Cost.
I do an API call to get activity detail which uses a serializer, and also wanted to add Cost serialized as well. So inside the ActivitySerializer I have tried this:
Class ActivitySerializer: < ActiveModel::Serializer
ActiveModel::Serializer.config.key_transform = :unaltered
attributes :id,
:name,
:description
...
has_many costs, each_serializer: CostSerializer
end
The CostSerializer looks like this:
class CostSerializer < ActiveModel::Serializer
ActiveModel::Serializer.config.key_transform = :unaltered
attributes :id,
:amount,
:description
end
The result is that Activity data looks good but Cost data give me this:
relationships":{"costs":{"data":[{"id":"20","type":"costs"}]}
Not sure why amount and description get dropped off. If I do this, it works (add listCosts to attributes in ActivitySerializer):
def listCosts
object.costs.map do |cost|
CostSerializer.new(cost, scope:scope, root: false, event: object)
end
end
The output is a bit different, doesn't have Relationship, but does have the serializer attributes that I want. I am using Rails 5.1.3 with AMS 0.10.
I'm assuming you're using the json_api adapter. As per the sample for the JSON API specification in http://jsonapi.org/examples/, any other attribute other than the "type" and "id" of the associated model can be exposed through the "included" property. You may checkout the discussion in https://github.com/rails-api/active_model_serializers/issues/1056