jsonapi icon indicating copy to clipboard operation
jsonapi copied to clipboard

url_for_pagination cannot handle nested resources

Open strzibny opened this issue 7 years ago • 3 comments

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?

strzibny avatar Apr 09 '19 17:04 strzibny

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 avatar Jun 22 '20 19:06 Stefano1990

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

Stefano1990 avatar Jun 22 '20 19:06 Stefano1990