Skip to content

Passing resource relationship in POST request #79

Description

@KidA001

I have two models that we'd like to be created in the same request.

Resource

module API
  module V1
    class ProjectToolboxTalkResource < JSONAPI::Resource
      attributes :date

      has_one :toolbox_talk
      has_one :superintendent
      has_one :project
      has_many :attendees
      has_many :project_toolbox_talk_users
    end
  end
end

POST Request

{
  "data": {
    "type": "project_toolbox_talks",
    "attributes": { "date": "2017-12-11" },
    "relationships": {
      "project_toolbox_talk_users": {
        "data": [
          { 
            "type": "project_toolbox_talk_users",
            "attributes": { "user_id": "559ff2c9-beb6-47cd-9757-66104617403b" }
          }
        ]
      },
      "projects": {
        "data": {
          "type": "projects", "id": "d9b28ffd-6f30-4dd0-a227-720caa9b881e"
        }
      }
    }
  }
}

When I make the POST request I get the following error even though I have linked project with has_one :project

{
  "errors": [
    {
      "code": "105",
      "detail": "projects is not allowed.",
      "status": "400",
      "title": "Param not allowed"
    }
  ]
}

What am I not understanding?

Activity

  1. tiagopog commented on Dec 17, 2017

    @tiagopog
    Owner

    Hey there, @KidA001!

    It's happening because you didn't defined projects as a relationship of project_toolbox_talks. Then you just need to add the following line to ProjectToolboxTalkResource :

    has_many :projects

    It's worth to mention that you may get in trouble trying to add project_toolbox_talk_users since attributes are not allowed for the relationship member:

    "project_toolbox_talk_users": {
      "data": [
        { 
           "type": "project_toolbox_talk_users",
           "attributes": { "user_id": "559ff2c9-beb6-47cd-9757-66104617403b" }
        }
      ]
    }

    Multiple operations are not present in the JSON API specs yet, but there are some cool workarounds (btw there is one identical to yours).

    So if you go for this workaround and start getting some error responses for using the attributes on relationship objects, I recommend you to extract its values and delete the key (attributes) from params[:project_toolbox_talk_users][n][:project_toolbox_talk_users].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions