Setting custom type on polymorphic association
Hey,
I have the following use case and wondering whether there's a way to solve it.
I have a polymorphic association and am using decorators, like so:
belongs_to :actor, polymorphic: true do |activity, params|
actor = activity.actor
UserAsActorDecorator.decorate(actor) if actor.class == UserActor
# etc...
end
The issue I'm facing is that the type infered in this case would be user_as_actor_decorator but I'd like to keep the original type of user_actor. At this point I'd like to set custom types on polymorphic associations. What I tried to do is to have a serializer for this class which sets the type correclty, i.e.
class V1::UserAsActorDecoratorSerializer
include FastJsonapi::ObjectSerializer
set_type :user_actor
end
That makes type correct in the included part, but within data it remains the same.
{
"data": [
{
"id": "1",
"type": "activity",
"relationships": {
"actor": {
"data": {
"id": "1",
"type": "user_as_actor_decorator"
}
}
}
}
],
"included": [
{
"id": "1",
"type": "user_actor"
}
]
}
I would've expected this to be the solution, but this actually breaks json:api functionality because relationships can no longer be correlated with included data.
The solution could be to
- keep types an sync (e.g. the ability to infer
record_typefrom the serializer) - be able to set
record_typedynamically on a polymorphic association
As far as I'm aware these are not possible. Could you recommend a workaround or would you consider this something to be addressed in the future?
I'm having this issue as well, this seems like a bug. But I'm no json-api expert.
It doesnt matter what options you try on the relation or in the serializer itself, it will always get its type from the object class.
For now, I just renamed the class, which is fine, but it would be great to have an option to override that in a polymorphic association.
I would take a crack at a PR if someone can point me in the right direction.