jsonapi-rb probleams with Relationsship

426 Views Asked by At

I have a problem with the gem jsonapi-rb, i try to used the relation in the serializable but it does work.

the models

class Customer < ApplicationRecord
  has_one :card
end

class Card < ApplicationRecord
  belongs_to :customer
end

The serializable

class SerializableCustomer < JSONAPI::Serializable::Resource
  type :customer
  attributes :id

  has_one :card do
    data do
      @object.card
    end
  end
end


class SerializableCard < JSONAPI::Serializable::Resource
  type :card
  attributes :id, :stripe_id, :exp_month

  belongs_to :customer do
    data do
      @object.customer
    end
  end
end

the customer already has a card but when i try to get the responds, only get in relations of customer, I dont get data about the card

SerializableCustomer.new(object: customer)

respond

{
  "id": "1",
  "type": "customer",
  "attributes": {
    "id": "1",
  },
  "relationships": {
    "card": {
      "meta": {
        "included": false
      }
    }
  }
}
1

There are 1 best solutions below

0
On

To have the data for the card relationship included. You need to include it in your initialization. By default, it will only serialize the linked data for a relationship, when you include it.

SerializableCustomer.new(object: customer, include: [:cards])

You can also include this when rendering your JSON.

render jsonapi: customer, include: [:cards]