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