2
votes

I'm using ActiveModel::Serializer in my rails-api app. I have a polymorphic association called addonable:

class AddOn < ActiveRecord::Base
  belongs_to :addonable, polymorphic: true
end
class Container < ActiveRecord::Base
  has_many :add_ons, as: :addonable
end
class Depot < ActiveRecord::Base
  has_many :add_ons, as: :addonable
end

Then, I have two different controllers, each of them returns a different addonable (Container or Depot). I would like the serializer to return the addonable association with its class name:

class DepotSelectSerializer < ActiveModel::Serializer
  attributes :id, :quantity

  belongs_to :addonable,  serializer: DepotSerializer, polymorphic: true
end
#returns: {:data=>{:id=>:string, :type=>:string, :attributes=>{:quantity=>:integer}, :relationships=>{:addonable=>{:data=>:object}}}}

#I want: {:data=>{:id=>:string, :type=>:string, :attributes=>{:quantity=>:integer}, :relationships=>{:depot=>{:data=>:object}}}}

I want the object to be in the relationships hash, not in the attributes, that's why I cannot use a custom method.

Ideally, I would have something like:

belongs_to :addonable,  serializer: ContainerSerializer, polymorphic: true, as: :depot

But I cannot find anything similar. Is this possible? Thanks in advance

1
For those who are using rails-api/active_model_serializers. It is possible to indicate :key. So in my case it would be belongs_to :addonable, serializer: DepotSerializer, polymorphic: true, key: :depot - hcarreras

1 Answers

0
votes

From active_model_serializer document, it describes:

You may also use the :serializer option to specify a custom serializer class and the :polymorphic option to specify an association that is polymorphic (STI), e.g.:

has_many :comments, :serializer => CommentShortSerializer

has_one :reviewer, :polymorphic => true

Serializers are only concerned with multiplicity, and not ownership. belongs_to ActiveRecord associations can be included using has_one in your serializer.

So in your case, let use has_one instead of belongs_to:

has_one :addonable, serializer: DepotSerializer, polymorphic: true

Tested, it works in my project!