我正在尝试执行替换唯一位置值的事务。当我重新插入节目时,即使我已经预装了节目并且我在变更集中使用了cast_assoc,剧集也不会附加。以下是文件:
show_controller.ex
original_show = Repo.get!(Show, id)
|> Repo.preload(:episodes)
old_position = original_show.position
%{"position" => new_position} = show_params
new_position = String.to_integer(new_position)
query = from(s in Show, where: s.position <= ^new_position, where: s.position > ^old_position)
shows = Repo.all(query) |> Repo.preload(:episodes) |> Enum.sort(&(&1.position < &2.position))
result = Repo.transaction(fn ->
Repo.delete!(original_show)
Repo.delete_all(query)
Enum.each shows, fn show ->
show = Map.put(show, :position, show.position - 1)
changeset = Show.changeset(show)
case Repo.insert(changeset) do
{:ok, show} -> show
{:error, changeset} -> Repo.rollback(changeset)
end
end
changeset = Show.changeset(original_show, new_show_params)
case Repo.insert(changeset) do
{:ok, show} -> show
{:error, changeset} -> Repo.rollback(changeset)
end
end)
show.ex
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:title, :position, :shuffle_episodes])
|> cast_attachments(params, [:large_artwork_url, :parallax_artwork_url])
|> cast_assoc(:episodes)
|> validate_required([:title, :position, :large_artwork_url, :parallax_artwork_url, :shuffle_episodes])
|> unique_constraint(:position)
end