jsonapi-rb / jsonapi-rails

Rails gem for fast jsonapi-compliant APIs.
http://jsonapi-rb.org
MIT License
318 stars 62 forks source link

KeyFormat breaks relationships #122

Open juni0r opened 3 years ago

juni0r commented 3 years ago

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": 'john.doe@email.org',
  },
  "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": 'john.doe@email.org',
  },
  "relationships": {
    "contact_groups": {
      "data": [
        {
          "type": "contactGroups",
          "id": "c88e3a19-f814-49d9-a458-40c2103f0003"
        }
      ]
    }
  }
}
oudesab commented 3 years ago

Hi, try it:

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