From 92c5f5f8a722ac1c2988aa439b9dd44ec0d5ff59 Mon Sep 17 00:00:00 2001 From: Mathias Wingert Date: Mon, 30 Sep 2024 15:58:20 +0200 Subject: [PATCH] feature: Reload episodes after creating a new or updating an existing episode --- lib/radiator/podcast.ex | 17 +++++++++++++++++ lib/radiator_web/live/episode_live/index.ex | 8 ++++++++ 2 files changed, 25 insertions(+) diff --git a/lib/radiator/podcast.ex b/lib/radiator/podcast.ex index f4c60b19..17774eb4 100644 --- a/lib/radiator/podcast.ex +++ b/lib/radiator/podcast.ex @@ -234,6 +234,23 @@ defmodule Radiator.Podcast do Show.changeset(show, attrs) end + @doc """ + A forced reload of preloaded associations. + Usefull when only the associations have changed and Show does need to be reloaded. + + ## Examples + + iex> reload_assoc(%Show{}, :episodes) + %Show{} + + iex> reload_assoc(%Show{}, (from e in Episode, where: e.show_id == ^show_id, order_by: [desc: e.number])) + %Show{} + + """ + def reload_assoc(%Show{} = show, fields_or_query) do + Repo.preload(show, fields_or_query, force: true) + end + @doc """ Returns the list of episodes. diff --git a/lib/radiator_web/live/episode_live/index.ex b/lib/radiator_web/live/episode_live/index.ex index e1fbb8e0..331113da 100644 --- a/lib/radiator_web/live/episode_live/index.ex +++ b/lib/radiator_web/live/episode_live/index.ex @@ -120,7 +120,11 @@ defmodule RadiatorWeb.EpisodeLive.Index do "episode_id" => episode.id }) + show = Podcast.reload_assoc(socket.assigns.show, [:episodes]) + socket + |> assign(:show, show) + |> assign(:episodes, show.episodes) |> put_flash(:info, "Episode created") |> push_patch(to: ~p"/admin/podcast/#{socket.assigns.show}/#{episode}") |> reply(:noreply) @@ -133,7 +137,11 @@ defmodule RadiatorWeb.EpisodeLive.Index do defp save_episode(socket, :edit, params) do case Podcast.update_episode(socket.assigns.episode, params) do {:ok, episode} -> + show = Podcast.reload_assoc(socket.assigns.show, [:episodes]) + socket + |> assign(:show, show) + |> assign(:episodes, show.episodes) |> put_flash(:info, "Episode updated") |> push_patch(to: ~p"/admin/podcast/#{socket.assigns.show}/#{episode}") |> reply(:noreply)