leon_cruz

leon_cruz

How to validate Ecto Associations properly?

Hello there, I’m getting some problems in validate associations in Ecto. I have two schemas, Video and Playlist (a playlist can have many videos). The Video schema has a following changeset:

def changeset(video, attrs \\ %{}) do
  video
    |> cast(attrs, [:name, :url, :playlist_id])
    |> validate_required([:name, :url, :playlist_id])
end

And Playlist has the following changeset:

def changeset(playlist, attrs \\ %{}) do
  playlist
    |> cast(attrs, [:name, :category])
    |> cast_assoc(:videos, required: true)
    |> validate_required([:name, :category])
end

What I want is when create a video, a playlist must be required, and when create a playlist, at least, one video has to be informed. This works for the video case, but when I try to create a playlist, there is a validation error on playlist_id of video. Anyone has some idea how to proceed with this? What I’m doing wrong? Thanks!

Most Liked

soup

soup

Sounds like you’re trying to build everything in one go? But since the playlist doesn’t exist yet, it doesn’t have an id, so it can it be given to the videos, so they fail their validation.

Confession: I can’t remember the last time I used cast_assoc personally, I set association ids manually. I also don’t like how IIRC you have to always give all the relationships in total which can be cumbersome.

I would do something like this, where its a two step transaction. You can also try ecto.multi.

###
### Writing this on my way out the door, so take it as a suggestion
###

def create_playlist_with_videos(name, category, videos) do
  # I normally have my own wrapper around transaction, so trying to remember
  # exactly without docs.
  Repo.transaction(fn ->
    with {:ok, playlist} <- create_playlist(name, category),
         # now playlist exists with an id so we can create videso
         {:ok, videos} <- create_playlist_videos(playlist, videos) do
      # transaction() wraps result in {:ok, _}
      %{playlist | videos: videos}
    else
      # can write this nicer, ideally the {:error, _} could just fall
      # out and fail the transaction
      {:error, e} -> rollback(e)
    end
  end)
end

defp create_playlist(name, category) do
  %Playlist{}
  # its ok to have more than one changeset function, i find it useful to
  # have at least a create_ and update_ as often they want different
  # validations.
  |> Playlist.create_changeset(name, category)
  |> Repo.insert()
end

defp create_playlist_videos(%Playlist{} = p, videos) do
  videos
  |> Enum.map(fn v ->
    %Video{}
    |>Video.create_changeset(playlist.id, v.name, v.url)
    |> Repo.insert()
  end)
  |> Enum.reduce({:ok, []}, fn
    # acc is error, perpetuate
    # you can use reduce_while to quit out
    _, {:error, e} -> {:error, e}
    # vid was ok, save and keep going
    {:ok, vid}, {:ok, vids} -> {:ok, [vids | vid]}
    # vid was error, return error (or collate all errors or ...?)
    # how you handle these errors is kind of application specific
    {:error, cs} _ -> {:error, :idk_lol}
  end)
end

e: you also probably want to put a null: false constraint in the database too if you haven’t.

al2o3cr

al2o3cr

cast_assoc combined with validate_required on the child schema’s foreign key will not work (see also a lot of the search results on this forum for cast_assoc). When you’re creating a Playlist, the related Video changesets need to be valid before the Playlist has an ID.

My suggestion to resolve this:

  • use a changeset function in cast_assoc(:videos, ...) that doesn’t cast or require playlist_id; that value will be set by the Ecto machinery automatically

  • if a video cannot be created without a playlist_id, enforce this at the database level with a null: false constraint on the column

A rule I find useful to help decide if something should be validated in a changeset function: is there a meaningful way to give feedback about a resulting error to the user? For instance, a blank name or category can show a “can’t be blank” message next to the UI for that value - what feedback could a missing playlist_id give?

leon_cruz

leon_cruz

i’ve already setup this

For this case, the message error will be like: “must be select a playlist”

leon_cruz

leon_cruz

This was my current solution. I’ve created two changeset functions. The first I use when create a video standalone, with the playlist_id validation and the second, I use in cast_assoc of Playlist changeset function. I don’t know if it is a good practice and if there is better way to do this

Where Next?

Popular in Questions Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
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
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
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
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
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 45766 226
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
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
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
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 42633 214
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement