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

url_for_pagination cannot handle nested resources #196

Open
strzibny opened this issue Apr 9, 2019 · 2 comments
Open

url_for_pagination cannot handle nested resources #196

strzibny opened this issue Apr 9, 2019 · 2 comments

Comments

@strzibny
Copy link
Contributor

strzibny commented Apr 9, 2019

I was trying to set up a nested resource:

e.g.

resources "/documents", DocumentController, only: [:index, :create, :show] do
    resources "/pages", DocumentPageController, only: [:index]
end

and creating a special view:

defmodule MyApp.API.DocumentPageView do
  use JSONAPI.View, type: "document_pages"

but in the link section the url_for_pagination (and therefore all default links) point to the /api/v1/document_pages instead of /api/v1/documents/1/document_pages.

Is there a way how to point the helper to the right URL without hardcoding?

@Stefano1990
Copy link

I don't know if you are still looking for a solution to this but there is a way to do this (I think). It is perhaps not the cleanest way but it works:

In your controller:

def index(conn, %{user_id: user_id}) do
  user = YourApp.Users.get_user!(user_id)
  messages = YourApp.Messages.get_messages_for_user(user)

  render(conn, "index.json", data: messages, nested_path: "/users/#{user_id}")
end

in your view file:

def url_for(_, conn) do
  if Map.has_key?(conn.assigns, :nested_path) do
    "#{conn.assigns.nested_path}#{namespace()}/#{type()}"
  else
    "#{namespace()}/#{type()}"
  end
end

This will produce this json:

{
    "data": [],
    "included": [],
    "links": {
        "first": "/users/1/messages?page%5Bpage%5D=1",
        "last": "/users/1/messages?page%5Bpage%5D=0",
        "next": null,
        "prev": null,
        "self": "/users/1/messages"
    }
}

@Stefano1990
Copy link

Stefano1990 commented Jun 22, 2020

However, I would like to add that it is questionable if you should nest resources in the context of a JSONapi anyway. See this discussion:
https://stackoverflow.com/questions/45574823/should-nested-relationships-be-reflected-in-urls-for-json-api

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