I'm building a rails app off a tutorial I found and am trying to use a JSONAPI Active Model Serializer to generate a response of that format.
In an initializer, I've put:
ActiveModelSerializers.config.adapter = :json_api
In my gemfile:
gem 'active_model_serializers', '~> 0.10.0.rc3'
I'm expecting two resource level keys, data and relationships as per the json-api specs. However, is not separating out the relationship to its own object. This is my request for /contacts.
{
"data": [
{
"id": "1",
"type": "contacts",
"attributes": {
"family-name": "La",
"given-names": "ch",
"company": {
"id": 1,
"name": "Lorem Inc",
"phone": "+1 (415) 555-1234",
"email": "[email protected]",
"website": "www.lorem.inc",
"address": "213 Main St. 94063 San Francisco, CA",
"customer_id": "10001",
"additional_info": "",
"created_at": "2017-01-31T05:47:02.024Z",
"updated_at": "2017-01-31T05:47:02.024Z"
},
"title": null,
"phone": null,
"email": null,
"website": null,
"address": null,
"customer-id": null,
"additional-info": null
}
}
]
}
Company is a belong_to for contacts. Here are my serializers.
class CompanySerializer < ActiveModel::Serializer
attributes :id, :name, :phone, :email, :website, :address, :customer_id, :additional_info
end
class ContactSerializer < ActiveModel::Serializer
attributes :id, :family_name, :given_names, :company, :title, :phone, :email, :website, :address, :customer_id, :additional_info
end
These are my models:
class Contact < ApplicationRecord
belongs_to :company
validates :family_name, presence: true
validates :given_names, presence: true
end
class Company < ApplicationRecord
validates :name, presence: true
end
Everything else is just default generated code from rails cli. I'm not sure what else I need to add here because it is my understanding the default rails behavior is to generate a response that will show everything in the serializer. I'm assuming that jsonapi adapter should separate that out for me.
What else do I need to do to get the jsonapi adapter working properly?
I was missing relationships in my serializer!
Also answered in x post
https://github.com/rails-api/active_model_serializers/issues/2044