jsonapi-rails icon indicating copy to clipboard operation
jsonapi-rails copied to clipboard

KeyFormat breaks relationships

Open juni0r opened this issue 5 years ago • 1 comments
trafficstars

I'm using JSONAPI::Serializable::Resource::KeyFormat for camel-cased keys. However this breaks inclusion of relationships when the relationship's name is subject to key transformation:

# app/resources/contact_resource.rb
class ContactResource < JSONAPI::Serializable::Resource
  extend JSONAPI::Serializable::Resource::KeyFormat

  type 'contacts'

  key_format ->(key) { key.to_s.camelize(:lower) }

  has_many :contact_groups

  attributes :name, :email # ...
end
# app/controllers/contacts_controller.rb
class ContactsController < ApplicationController
  def index
    render jsonapi: Contact.all, include: [:contact_groups]
  end
end

Results in

# GET /api/v1/contacts
{
  "id": "046ffaf3-9c7b-4f36-a33b-1948cb889200",
  "type": "contacts",
  "attributes": {
    "name": "John Doe"
    "email": '[email protected]',
  },
  "relationships": {
   "contactGroups": {
      "meta": {
        "included": false
      }
    }
  }
}

Without using the key_format it works as expected:

# GET /api/v1/contacts
{
  "id": "046ffaf3-9c7b-4f36-a33b-1948cb889200",
  "type": "contacts",
  "attributes": {
    "name": "John Doe"
    "email": '[email protected]',
  },
  "relationships": {
    "contact_groups": {
      "data": [
        {
          "type": "contactGroups",
          "id": "c88e3a19-f814-49d9-a458-40c2103f0003"
        }
      ]
    }
  }
}

juni0r avatar Oct 23 '20 16:10 juni0r

Hi, try it:

render jsonapi: Contact.all, include: [:contactGroups]

oudesab avatar Apr 02 '21 12:04 oudesab