From 984c1c852324221eab0b6dcd72e0b69b760dc66b Mon Sep 17 00:00:00 2001 From: Berenice Medel Date: Wed, 17 Nov 2021 15:32:09 -0600 Subject: [PATCH] decrement songs_number when a song is deleted --- lib/live_beats/media_library.ex | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/live_beats/media_library.ex b/lib/live_beats/media_library.ex index 2a413d0..b4fd49b 100644 --- a/lib/live_beats/media_library.ex +++ b/lib/live_beats/media_library.ex @@ -333,7 +333,19 @@ defmodule LiveBeats.MediaLibrary do ) end - Repo.delete(song) + Ecto.Multi.new() + |> Ecto.Multi.delete(:delete, song) + |> Ecto.Multi.update(:update_songs_number, fn _ -> + user = Accounts.get_user!(song.user_id) + + user_params = %{ + songs_number: user.songs_number - 1 + } + + Accounts.User.songs_changeset(user, user_params) + end) + |> Repo.transaction() + end def change_song(song_or_changeset, attrs \\ %{})