innocentoldguy

innocentoldguy

Dynamically add and delete nested model data in a LiveView form

Ecto noob question here. I followed this tutorial for dynamically adding and deleting the many side of a one-to-many relationship in a Phoenix LiveView: Nested model forms with Phoenix LiveView · FullstackPhoenix

Just to keep it easy, lets say I have a one-to-many relationship between a Blog and its Comments.

Using the example in the above tutorial, I can dynamically add multiple Comments to a Blog. I can also delete Comments. If I delete a Comment that is in the changset, but not committed to the database yet (one with a temp ID), then I can continue to add more Comments. However, if I delete a Comment that is already in the database and then try to add another Comment, I get this error:

(RuntimeError) cannot replace related %Test.Blogs.Entry{__meta__: #Ecto.Schema.Metadata<:loaded, "comments">, delete: nil, id: 1, inserted_at: ~N[1970-01-01 00:00:00], blog: #Ecto.Association.NotLoaded<association :blog is not loaded>, blog_id: 1, temp_id: nil, title: "Test Blog", updated_at: ~N[1970-01-01 00:00:00]}. This typically happens when you are calling put_assoc/put_embed with the results of a previous put_assoc/put_embed/cast_assoc/cast_embed operation, which is not supported. You must call such operations only once per embed/assoc, in order for Ecto to track changes effeciently [sic].

My code is exactly the same as the code in the tutorial at this point, only with different table names. I’m using the latest versions of Phoenix, LiveView, and Ecto.

I’ve scoured the Ecto documentation for about 10 hours now, but I haven’t found a way to get past this error using Ecto changesets, as described in the tutorial. Is there a way to fix this error, or is it just impossible to use Ecto in the way this tutorial suggests?

First Post!

innocentoldguy

innocentoldguy

I misspoke in my original post. The tutorial I mentioned doesn’t show how to delete existing “Comments” from a “Blog.” I added that using this function:

def handle_event("remove-existing-comment", %{"remove" => id}, socket) do
    deleted_comments = [ id | socket.assigns.deleted_comments ]
    Blog.delete_comment(id)

    comments =
      socket.assigns.blog.commets
      |> Enum.reject(fn comment ->
        comment.id in deleted_comments
      end)

    changeset =
      socket.assigns.changeset
      |> Ecto.Changeset.put_assoc(:comments, comments)

    {:noreply, assign(socket, changeset: changeset, deleted_comments: deleted_comments)}
  end

This works fine, but if I delete an existing comment using this callback, then the function to create new Comments stops working, with the error I mentioned in my original post.

I apologize for attributing this part of the code to the author of the tutorial.

So, again, is there a way to get this to work with Ecto, or is it an impossible scenario?

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