ecto-nested-associations
Installation
SKILL.md
Ecto Nested Associations
RULES — Follow these with no exceptions
- Use
cast_assoc/3for has_many/has_one — never manually insert children in a separate step; let Ecto manage the relationship - Use
Ecto.Multifor operations spanning multiple unrelated tables — not nested changesets; Multi provides explicit rollback control - Set
on_deleteexplicitly in migrations —:delete_allfor owned children,:nothingfor references to independent entities - Always create indexes on foreign key columns — missing FK indexes cause slow joins and lookups on the child table
- Use
on_replace: :deleteincast_assocfor list management — allows removing items by omitting them from the input - Preload associations before updating them —
cast_assoc/3raises (attempting to cast or change association ... that was not loaded) if the association isn't preloaded; preload before update
cast_assoc for Nested Creates
Create parent and children in a single operation. Ecto sets foreign keys automatically.