This might be considered too non-specific a question, but I’m sure others have come up against this kind of conundrum, so it might just warrant being asked!
I have two models: Users and Surveys. My goal is to edit/save records from the Index view. In the Index view, each User row will have two select lists and some checkboxes. The select lists are populated with the names of all the available Surveys.
The purpose is to allow an admin to assign two Surveys to each user; to edit and save the records, right from the Index view. Currently, associations take place via a hasMany Through association: the intermediary model is called SurveyAssignments (I can’t do HABTM because I’m storing meta info).
What I’m struggling with is this: I can’t figure out how to save all those associations from the view. What’s making it tricky is the fact that each user will have a different association “state”: some users will have association records, some will not. Some will need associations created, others updated or removed. New users will be added to the system, but will still appear in the list with currently existing users, who already have associations.
There’s also an issue with constraint: each user will only ever have a maximum of two SurveyAssignment records associated with them.
Again, it’s the logic that I can’t wrap my head around: how can I save multiple records from one view, accounting for each User’s unique association states, all without getting overly bloated or complex? Are there any Cake methods I’m missing that could simplify the situation?
The main issue I was having was trying to save edits AND new records simultaneously. As it turns out, Cake’s automagic can take care of this.
When you run a saveMany or saveAll, if you don’t include an ID for a record, it creates a new record. If you do include an ID, Cake updates the pre-existing record.