rauversion-ror icon indicating copy to clipboard operation
rauversion-ror copied to clipboard

Fix nested forms duplicates in event schedule updates

Open Copilot opened this issue 1 month ago • 0 comments

Rails nested attributes with non-sequential indices cause duplicate record creation. When deleting schedules, gaps in array indices (e.g., [0, 3, 5]) prevent Rails from matching existing records by ID, creating duplicates instead of updating.

Changes

Frontend (Schedule.jsx)

  • Separate destroy operations from create/update operations
  • Ensure sequential indices: destroyed items first (0..N), then kept items (N+1..M)
  • Apply same logic recursively to nested schedule_schedulings_attributes

Backend (update.json.jbuilder)

  • Add error propagation for nested schedule_schedulings validations

Tests (event_schedules_update_spec.rb)

  • Add specs covering create, update, delete, and mixed operations
  • Verify no duplicates for both schedules and nested schedulings

Example

Before (incorrect):

// Non-sequential indices with gaps
formData.append(`event[event_schedules_attributes][0][id]`, 1)
formData.append(`event[event_schedules_attributes][0][_destroy]`, '1')
formData.append(`event[event_schedules_attributes][3][id]`, 2)  // Gap!
formData.append(`event[event_schedules_attributes][5][name]`, 'New')  // Gap!

After (correct):

// Sequential indices, destroy first
const itemsToDestroy = items.filter(i => i._destroy && i.id)
const itemsToKeep = items.filter(i => !i._destroy)

itemsToDestroy.forEach((item, idx) => {
  formData.append(`event[event_schedules_attributes][${idx}][id]`, item.id)
  formData.append(`event[event_schedules_attributes][${idx}][_destroy]`, '1')
})

itemsToKeep.forEach((item, idx) => {
  const formIndex = itemsToDestroy.length + idx
  // ... append with formIndex
})
Original prompt

cuando edito horarios en eventos Schedule.tsx, a veces las insersiones quedan repetidas muchas veces, eso está mal, o a veces las eliminaciones quedan mal. estamos enviando parametros form y manejando los nested forms. debemos solucionar eso de manera que la actualizacion de campos es consistente. revisa bien la implementation y del backend para ver que todo ande en orden


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot avatar Nov 18 '25 01:11 Copilot