New topic Closed topic
avatar image
1
How to update a Has And Belongs To Many field
By Created , last editted

What is the best approach to update an HABTM field.

Scenario:

I have an 'new-message' endpoint in which I have a multi-select input field, that is filled with available tags (from a 'tags' collection variable based on model: tags). 

In an action on the Post endpoint managed to create a new message and to retrieve the tag id's as an array (collection) and I am using a loop to select each tag object from the 'tag' model. Then using an update on the new-message object I am adding each tag object into the HABTM tag field from that new-message object. So far, so good.

Now I want to be able to update the tags that are linked to the message:

My first thought is to do the following:

  1. I create a collection of all currently linked 'tags' from the specific message
  2. I loop trough this collection of step 1, and remove all these 'tags' from the message
  3. I will then loop through the edited collection of 'tag_id's' that I retrieve from the Post endpoint to select each ready-to-link 'tag' object.
  4. I update the message object (which doesn't have any tags linked - see: step 2) and add all the 'tag' objects from step 3.

Question:

Is this approach the best approach to follow? If not, what is the alternative?


What is the best approach to update an HABTM field.

Scenario:

I have an 'new-message' endpoint in which I have a multi-select input field, that is filled with available tags (from a 'tags' collection variable based on model: tags). 

In an action on the Post endpoint managed to create a new message and to retrieve the tag id's as an array (collection) and I am using a loop to select each tag object from the 'tag' model. Then using an update on the new-message object I am adding each tag object into the HABTM tag field from that new-message object. So far, so good.

Now I want to be able to update the tags that are linked to the message:

My first thought is to do the following:

  1. I create a collection of all currently linked 'tags' from the specific message
  2. I loop trough this collection of step 1, and remove all these 'tags' from the message
  3. I will then loop through the edited collection of 'tag_id's' that I retrieve from the Post endpoint to select each ready-to-link 'tag' object.
  4. I update the message object (which doesn't have any tags linked - see: step 2) and add all the 'tag' objects from step 3.

Question:

Is this approach the best approach to follow? If not, what is the alternative?

  • Avatar image
    Hi Frans, What do you want to achieve with the action?
    By
  • Login to reply
Answers
Sort by:

This topic is closed.