spyke icon indicating copy to clipboard operation
spyke copied to clipboard

Associations through nested JSON response

Open srozen opened this issue 2 years ago • 1 comments

Hello, is there a way to make the association definition to pick up nested resources from the JSON payload?

Let's say we have a Shop model with Articles and Employees, but the JSON payload when fetching the Shop is the following :

{ 
  "id": 1,
  "resources": {
    "employees": [],
    "articles": [],
  }
}

How could one define the has_many such that shop.employees returns the Spyke association?

srozen avatar Nov 07 '23 14:11 srozen

@srozen there is!

...unfortunately it expects the JSON to appear in a certain way though, ie:

{ 
  "id": 1,
  "employees": [],
  "articles": [],
}

...so in your example a bit of a workaround may be required. 🤔

You could either massage the incoming JSON in Faraday before passing it on to Spyke to fit the format above, or perhaps use a class to join them together:

class Book < Spyke::Base
  has_one :resources, class_name: "BookResources", uri: nil
end

class BookResources < Spyke::Base
  has_many :employees, uri: nil
  has_many :articles, uri: nil
end

book.resources.employees # => []
book.resources.articles # => []

balvig avatar Nov 15 '23 06:11 balvig