Netflix / fast_jsonapi

No Longer Maintained - A lightning fast JSON:API serializer for Ruby Objects.
Apache License 2.0
5.07k stars 425 forks source link

Setting custom type on polymorphic association #397

Open thisismydesign opened 5 years ago

thisismydesign commented 5 years ago

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

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?

zion commented 5 years ago

I'm having this issue as well, this seems like a bug. But I'm no json-api expert.

zion commented 5 years ago

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.