Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Associations through nested JSON response #149

Open
srozen opened this issue Nov 7, 2023 · 1 comment
Open

Associations through nested JSON response #149

srozen opened this issue Nov 7, 2023 · 1 comment

Comments

@srozen
Copy link

srozen commented Nov 7, 2023

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?

@balvig
Copy link
Owner

balvig commented Nov 15, 2023

@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 # => []

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants