DavyJonesLocker / postgres_ext-serializers

MIT License
324 stars 30 forks source link

Breaks polymorphic relationships in Ember Data #25

Open mcm-ham opened 9 years ago

mcm-ham commented 9 years ago

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: https://github.com/emberjs/data/issues/1574 Without postgres_ext-serializers installed polymorphic relationships are serialized as:

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

Which ember data does support.

BenMorganIO commented 9 years ago

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

felixbuenemann commented 8 years ago

This could probably be solved by reflecting on the association.

felixbuenemann commented 8 years ago

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

felixbuenemann commented 8 years ago

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.