Skip to content

Polymorphic association on JSON API #1448

Closed
@joaomdmoura

Description

@joaomdmoura

When using JSON-API with polymorphic associations there is a strange behavior, instead of using the name of the resource it chooses to use the name assigned to the polymorphic relation.

This is not wrong ©️, but if you think about the most of JS clients frameworks around, it makes more sense to use the resource's name.

Here is as example to illustrate:

model/address.rb

class Address < ActiveRecord::Base
  belongs_to :addressable, polymorphic: true
end

model/user.rb

class Address < ActiveRecord::Base
  has_one :home_address, as: :addressable, class_name: 'Address', dependent: :destroy
end

The serialized JSON output for address will be:

'data': {
  'id': 1,
  'type': 'addresses',
  'attributes': {
    ...
  },
  'relationships':  {
    'addressable': {
      'data': {
        'id': 1,
        'type': 'users'
      }
    }
  }
}

My point is related to this part:

  'relationships':  {
    'addressable': {
      'data': {
        'id': 1,
        'type': 'users'
      }
    }
  }
}

Despite of being a user the root name of this node is addressable, and IMO it should be user.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions