DavyJonesLocker/postgres_ext-serializers

Breaks polymorphic relationships in Ember Data

mcm-ham opened this issue · 4 comments

With postgres_ext-serializers installed polymorphic relationships are serialized as:

images: [{
  id: 1,
  imageable_id: 1,
  imageable_type: 'User'
}]

Which ember data does not support: emberjs/data#1574
Without postgres_ext-serializers installed polymorphic relationships are serialized as:

images: [{
  id: 1,
  imageable: {
    id: 1,
    type: 'User'
  }
}]

Which ember data does support.

I feel like this could be a simple fix. Is there a way to detect if the object is polymorphic?

This could probably be solved by reflecting on the association.

It seems this was fixed in emberjs/data#1662 so imageable_id and imageable_type should just work.

Adding proper support for polymorphic associations also requires mangling the content of the type column.

Example:

module Foo
  class Asset
    belongs_to :viewable
  end

  class User
  end

  class AssetSerializer
    embed :ids, include: true
    attributes :id
    has_one :viewable, polymorphic: true
  end

  class UserSerializer
    attributes :id
  end
end

user = Foo::User.create
=> #<Foo::User id:1>
asset = Foo::Asset.create(viewable: user)
=> #<Foo::Asset id:1, viewable_id: 1, viewable_type: "Foo::User">
Foo::AssetSerializer.new(asset).as_json
=> {:users=> [{:id=>1}], :asset=>{:id=>1, :viewable=>{:type=>:user, :id=>1}}}

Resulting JSON:

{
   "users" : [
      {
         "id" : 1
      }
   ],
   "asset" : {
      "id" : 1,
      "viewable" : {
         "type" : "user",
         "id" : 1
      }
   }
}

As can be seen, AMS removes the module names from the types and changes them to underscored notation.