Side effects in changesets - is this a recommended pattern?

The Ecto documentation has a section on upserting associations and I noticed that they accomplish this by having the changeset include operations that will automatically do the upsert. This seems surprising to me as this means that every invocation of the changeset will involve DB operations. I could see this being particularly problematic if this changeset was tied to a form with live validation happening in response to user inputs.

Is this a recommended pattern? Are there any alternatives if I wanted to accomplish something similar?

1 Like

I think the more common pattern is mentioned at the bottom of that guide

The downside of this approach is that tags will be created even if creating the post fails, which means some tags may not have posts associated to them. In case that’s not desired, the whole operation could be wrapped in a transaction or modeled with Ecto.Multi.

I’m not too sure why the guide does it that way. I don’t think it’s a common approach (though I might be wrong). It might be for illustrative purposes and trying to keep the user from having to think about the transaction functions.

3 Likes