Ecto put_assoc() Unexpected Behavior with many_to_many Relationships

98
clicks
Ecto put_assoc() Unexpected Behavior with many_to_many Relationships

Source: reddit.com

Type: Discussion

The author blah1998z shared a problem encountered while working with Ecto, a database wrapper for Elixir that provides a domain-specific language for writing queries and interacting with databases. They shared a code snippet from an Ecto.Schema defining a many_to_many relationship between `ItemA` and `ItemB`, specifying `on_replace: :delete` for the association. When attempting to update an `ItemA` record with associated `ItemB` records using `put_assoc()`, they expected Ecto to handle existing associations intelligently, either recognizing already-present data or replacing the mapping. However, they observed that `put_assoc()` was deleting all entries from the mapping table without reinserting them upon update. Only on a subsequent identical update would the IDs be re-inserted, and then once again removed on the next update. This led the author to question if there's a misunderstanding of `put_assoc()`'s intended behavior since it is removing the structs that were provided.

© HashMerge 2024