Executing code on successful update/insert/delete

Hi,

I am looking for a way to execute a function on successful transactions on a schema. In Active Record terms, this would be a “hook” or “callback”. My intuition says that belongs in the changeset, however they are evaluated before the actual transaction; which is too early.

My concrete scenario: Deleting caches on any update / insert / delete of a certain schema.

Thanks,
Eric

Since Elixir and Ecto favour the explicit over the implicit your would generally follow as the doc examples show:

case MyRepo.update post do
  {:ok, struct}       -> 
    post_update_actions(struct)
  {:error, changeset} -> 
    error_processing_or_retry(changeset)
end

If this is a common pattern then you might consider adding your own wrapper functions in the repo.

1 Like

Thanks, that makes sense. I was looking for a single place to put the code but I already have that (in Phoenix): the update function in the context. Great :slight_smile: