jsonapi-utils icon indicating copy to clipboard operation
jsonapi-utils copied to clipboard

Passing resource relationship in POST request

Open KidA001 opened this issue 6 years ago • 1 comments

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?

KidA001 avatar Dec 11 '17 22:12 KidA001

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].

tiagopog avatar Dec 17 '17 15:12 tiagopog