Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Passing resource relationship in POST request #79

Open
KidA001 opened this issue Dec 11, 2017 · 1 comment
Open

Passing resource relationship in POST request #79

KidA001 opened this issue Dec 11, 2017 · 1 comment

Comments

@KidA001
Copy link

KidA001 commented Dec 11, 2017

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?

@tiagopog
Copy link
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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants