pwightman

pwightman

Ecto: How to force overwrite embeds_many update

I’ve recreated a minimal example of the problem I’m experiencing, where cast_embed on a embeds_many is trying to protect me from accidentally overwriting my embeds when I don’t want it to. Given the following code:

defmodule TaskList do
  primary_key false
  embedded_schema do
    embeds_many :tasks, Task
  end

  def changeset(data, params \\ %{}) do
    data
    |> cast(params, [])
    |> cast_embed(:tasks)
  end
end

defmodule Task do
  @primary_key false
  embedded_schema do
    field: title
  end

  def changeset(data, params \\ %{}) do
    data
    |> cast(params, [:title])
    |> validate_required(:title)
  end
end

# Below called when LiveView form submitted

def handle_event("submit", params, socket) do
  # task_list already has 3 Task structs assigned to `tasks`, when loaded from DB
  task_list = socket.assigns.task_list

  result =
    task_list
    |> TaskList.changeset(params["data"])
    |> Repo.update()

  case result do
    {:ok, task_list} ->
      # redirect, etc
    {:error, changeset} ->
      # handle error
  end
end

TaskList.changeset/2 will raise an exception because I’m trying to replace the existing 3 Task embeds with new ones, and on_replace defaults to :raise.

Elsewhere in my app, I’m using embeds_one :foo, Foo, on_replace: :update , which has exactly the semantics I want, however embeds_many does not support this option, and none of the available options (:raise, mark_as_invalid, :delete) has the correct semantics. I would just like any cast_embed(:tasks) to “update/replace” what is there.

Right now I’m doing a dance where I replace the existing list with an empty list if I will be calling cast_embed, but it feels like a hack, and I’m replicating this hack in multiple places, and it makes the code quite messy and hard to reason about (esp when there’s other logic that conditionally calls cast_embed).

Any ideas how to do this simply?

Marked As Solved

LostKobrakai

LostKobrakai

If you don’t use primary keys what would be the difference between on_replace: :delete and on_replace: :update in the first place? This is besides the fact that for embeds_many you cannot use :update for replaced items, because there’s no way to know which old item shall be updated with which set of new data. Even less given you don’t have primary keys on your embeds.

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement