You could use with statements if there are multiple failures possible.
However i think this does not fundamentally solves what you are trying to achieve. Maybe Ecto.Multi would be a better choice if you need to move files around as part of the transaction.
Its kind of hard to understand what is going on exactly in the snippet you posted. If it is one form, i guess you probably should have 1 changeset, also prepare_changes/2 allows you to run code in the transaction.
Using with instead of nested case statements could look like this: (i did not mess with the changeset)
def create_recording(attrs \\ %{}) do
Repo.transaction(fn ->
with {:ok, recording} <- insert_recording(attrs),
{:ok, with_audio} <- update_recording(recording) do
with_audio
else
{:error, error} ->
Repo.rollback(error)
end
end)
end
defp insert_recording(attrs \\ %{}) do
%Recording{}
|> Recording.changeset(attrs)
|> Repo.insert()
end
defp update_recording(recording, attrs \\ %{}) do
recording
|> Recording.audio_changeset(attrs)
|> Repo.update()
end
If you are uploading a file and don’t want to depend on ids from the db, generate a random path for the uploaded file (eg uuid as filename). Maybe this helps you to get rid of the second changeset … You would probably still need a transaction to move/upload the file. Just be aware that storing a lot of files inside 1 directory is a performance killer.


















