graphiti icon indicating copy to clipboard operation
graphiti copied to clipboard

POST request with relationship but no included tries to update the resource in the relationship

Open andhapp opened this issue 4 years ago • 2 comments

I am using json_api_client for making API requests. We inject a request modifier to ensure the POST/PUT request payload matches Graphiti's sideposting format.

However, here's a request that's stumped me. How should this POST request with the following payload behave?

{
  data: {
    id: '1',
    type: 'posts',
    attributes: { title: 'My Title' },
    relationships: {
      author: {
        data: {
          id: '1',
          type: 'authors'
        }
      }
    }
  }
}

Post(id, title, author_id) and Author(id, first_name, last_name) are activerecord models.

PostResource has a belongs_to relationship with AuthorResource

Current behaviour: It tries to update Author activerecord model and fails due to some newly added validation. Not sure why it tries to update the Author.

Expected behaviour: It should create a new POST record with title: 'My Title' and author_id: 1

andhapp avatar Apr 14 '20 17:04 andhapp

I'd say it's expected but something we can improve. Right now each entity goes through the same codepath regardless of if attributes are passed or not (normally, nothing would happen when no validations). I'd be happy to accept a PR improving this, but you could also work around it using persistence hooks (check to see if only id is passed, if so avoid saving). Check out this guide for more on customizing persistence.

richmolj avatar Apr 15 '20 13:04 richmolj

Thanks, before_save came to my rescue.

I'd be happy to accept a PR improving this

I will be happy to do a PR, but no idea, where to even start with it. Any guidance will be really appreciated.

andhapp avatar Apr 20 '20 16:04 andhapp