KiKi

KiKi

Adding and removing elements from jsonb field using embedded schema

I’m working on a small project where I’m trying to learn how to use embedded schemas. So I have albums and tracks. Album can have many tracks and they are saved in jsonb field using embedded schema. I want to be able to add new tracks and also, delete them.

In create_track() function, first I get existing tracks, then there is a map with a new track and then they both get merged, put into changeset and album get updated.

def create_track(%Album{} = album, attrs \\ %{}) do
    existing_tracks = album.tracks
    
    new_track = 
      %TrackEmbed{
        # this is just to show how TrackEmbed looks, real data comes from attrs
        name: "track name"
      }
      
    tracks = [new_track | existing_tracks]
    changeset = Ecto.Changeset.change(album)

    changeset
    |> Ecto.Changeset.put_embed(:tracks, tracks)
    |> Repo.update()
  end

To delete a track, I get existing tracks, find a list index where track I want to delete is and then I remove it from the list and the album gets updated.


def delete_track(%Album{} = album, attrs \\ %{}) do
    existing_tracks = album.tracks
    
    # real data comes from attrs here too
    existing_track_index = Enum.find_index(existing_tracks, fn x -> x.name == "track name" end)
    
    tracks = List.delete_at(existing_tracks, existing_track_index)
    changeset = Ecto.Changeset.change(album)

    changeset
    |> Ecto.Changeset.put_embed(:tracks, tracks)
    |> Repo.update()
end

The code I have here works but here I’m getting an existing list and just adding or removing from it, so I was wondering if there is maybe a better way?

Marked As Solved

dimitarvp

dimitarvp

Nothing dramatically better exists, as far I am aware. You could use cast_embed but that doesn’t help you much because you would still need to load the old value of the list and then update it, meaning that put_embed is the better choice here since it assumes the exact same use case.

cast_embed would be a good choice if you were receiving an entirely new list with which overwrites the old one (and usually if that new list is coming from external request).

Where Next?

Popular in Questions Top

New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
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

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
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
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 47930 226
New
Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement