2

I would like to know how I should update many-to-many relationships in my API.

My app has companies that can have many tools and technologies. The relationship is stored in joining tables companies_technologies and companies_tools.

The frontend has a form to edit the company. I would like the users to submit a single form to update (1) company info, (2) the tools, and (3) technologies.

The actual form

My solution is to send PUT request to the server with the following data:

{
  ...company attributes...,
  tool_ids: [1,2,3,4],
  technology_ids: [11,22,33,44]
}

Then in the server, I would find all tools that belong to the company, get their ids, find the difference between those ids and tool_ids, and insert/delete to companies_tools table. Same for technology_ids.

But such an approach feels kind of clunky. Is there an alternative approach, or how can I improve my solution?

  • Answer is fine. Alternative is so see a CompanyTool as a resource on /companies/(id)/tools. Then when you add one just send a post. When you remove send a delete. You could do that from the client directly or in your controller you could split up a complete post and make multiple requests internally. This becomes useful when you want to add for example a tool version to the tool. – Luc Franken Aug 17 '16 at 8:58
3

Nothing clunky about this. Just straight up send the data to update with. Though I'm making a few assumptions:

I'm going to just assume the "tools" you're referring to are what you labeled "communication methods".

I'm assuming when sending this PUT, tech and tools are constrained to existing id's. Meaning if the user wants to add a new tool when typing you either disallow this or send a different rest update to create the tool, learn its id, and use that new id in this PUT.

  • Your assumptions are correct. Thanks for the clarification. – Sung Cho Aug 17 '16 at 4:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.