Skip to content

docs: clarify index shifting in cast_assoc/3 when using drop_param#4705

Merged
josevalim merged 3 commits intoelixir-ecto:masterfrom
JuanmiAcosta:docs/clarify-cast-assoc-reindexing
Feb 16, 2026
Merged

docs: clarify index shifting in cast_assoc/3 when using drop_param#4705
josevalim merged 3 commits intoelixir-ecto:masterfrom
JuanmiAcosta:docs/clarify-cast-assoc-reindexing

Conversation

@JuanmiAcosta
Copy link
Contributor

While the behavior of :drop_param and :sort_param is documented, this PR adds a specific clarification regarding the index shifting that occurs when elements are dropped but not explicitly re-sorted.

Context:

When using a map for many-style associations, Ecto compacts the remaining elements into a sequential list after applying :drop_param. As a result, the index passed to an arity-3 :with function reflects the final position in the list, which might differ from the original map key.

Contribution:

  • Explicitly mentions that remaining elements are re-indexed sequentially starting from 0.

  • Adds a visual example to illustrate the difference between the original parameter key and the final position received by the changeset function.

This addition aims to help developers avoid subtle bugs when using the :with option to persist order (e.g., in a :position column), making the underlying list transformation more explicit.

Note: This is my first contribution to Ecto (and to an open-source project). I've found this specific case while working on a production system and thought it would be a valuable addition to the documentation for other developers. Feedback is more than welcome!

The element originally at index `2` ("Third St") will be passed to the `:with`
function with position `1`, because the list is compacted after the drop
operation. If you need to preserve the original semantic positions, ensure
you also provide a `:sort_param`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we preserve the original positions even with sort_param? If an element is removed, no element can ever be at index 2, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, the positions are not preserved since the collection is compacted into a list. I'm removing that last line. Thanks for the feedback, I appreciate it! -> 1268a5a

@josevalim
Copy link
Member

Thank you and congratulations @JuanmiAcosta on your first PR! ❤️ I have dropped one tiny question!

@josevalim josevalim merged commit 3be4e60 into elixir-ecto:master Feb 16, 2026
@josevalim
Copy link
Member

💚 💙 💜 💛 ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants