Skip to content

[RFC]Thoughts on an explicit way to define nested relationships? #1113

Closed
@NullVoxPopuli

Description

I've been working on sideloading (#1107) for the json adapter, and needed recursive relationship building of the json object.

The problem with doing a strictly recursive approach (independent of sideloading or not), is that if you have enough references on your objects to other objects, a single request (of any kind) is basically going to return the whole database.
Example: Post belongs_to an Author which has_many Posts, and each Post has_many Comments, and each Comment belongs_to an Author.... it and would just keep going. The code in #1107 at least doesn't allow for things to be serialized multiple times (like if a post has the same author, that author only gets serialized once).

So, a potential solution that I'm working on prototyping right now is something like this:

PostSerializer < #...
  has_many :comments, include: :author
end

So, instead of recursively serializing the comments, we'd serialize them like we do today, but because we have the author key in the include hash, we'd also serialize each of the coments' authors.

BlogSerializer < #...
  has_many :posts, include: { author: [:bio], comments: [:author]] }
end

resulting json may look like:

{
  blog: {
    posts: [
      {
        author: {
          bio: {...}
        },
        comments: [
          {  author: {...} }
        ]
      }
    ]
  }
}

or

AuthorSerializer < #...
  has_many :blogs, include: { posts: [:author, comments: :author] }
end

resulting json may look like:

{
  author: {
    blogs: [
      {
        posts: [
          {
            author: {..}
            comments: [
              {
                author: {..}
              }
            ]
          }
        ]
      }
    ]
  }
}

this gets in to a problem of potentially having redundant data in the resulting json, so caching would be super important here (which I think is implemented by default? or does a cache key need to be specified in the controller? if not, should there be a default? - or would this kind of cacheing be separate, and more like fancy memoization?)

Note, I found that there was a previous attempt at solving this problem here: #952, but I think it's not clear in #952 how deep the nested relationships go / it could imply that the same recursive problem exists.

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions