
How to update a Has And Belongs To Many field
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:
- I create a collection of all currently linked 'tags' from the specific message
- I loop trough this collection of step 1, and remove all these 'tags' from the message
- 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.
- 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:
- I create a collection of all currently linked 'tags' from the specific message
- I loop trough this collection of step 1, and remove all these 'tags' from the message
- 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.
- 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?
-
Hi Frans, What do you want to achieve with the action?