Search code examples
elixirphoenix-frameworkectonested-resources

Why Phoenix require all nested resource in the parameter, Using cast_assoc or put_assoc


The case is one_to_many and I want to insert and update necessity minimum nested resources at the same time.

According to https://hexdocs.pm/ecto/Ecto.Changeset.html#cast_assoc/3, cast_assoc require us to update/insert nested resource with all associations in the parameter. If we don't include all associations, cast_assoc invoke :on_replace action for the missing associations.

I think it’s OK to work with the form generated by Phoenix templates because form sends all association in the parameter every time. But if this function works with JS frameworks, I can send necessity minimum associations which are changed on a web browser. In such a use case, may I repeat update in a transaction as well or do same as a template does?

I feel a little bit tricky for that behavior. And I feel it's better to add action explicitly into the parameter instead of :on_replace

What do you think about it?


Solution

  • It's not a Phoenix requirement, it's an Ecto requirement. If Ecto does not have all of the information pertaining to your schema then it cannot reliably create an accurate changeset.

    I'm not really understanding your specific question, but if you want to update the record without re-supplying associations, then create a separate changeset function that doesn't touch the association.