leon_cruz
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!
Trending in Questions
Hey guys,
I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly
Do you guys have any suggestions what is the best prac...
New
Hello!
Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app.
I creat...
New
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
I’m trying to set up Emacs with elixir-ls via lsp-mode and credo via Flycheck. This should mostly be preconfigured as Flycheck picks up c...
New
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixirconf-us
- #elixir-ls
- #ai
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 8- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
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_assocpersonally, 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.
e: you also probably want to put a
null: falseconstraint in the database too if you haven’t.soup
Oh I meant to mention, you can of course still use
cast_associf you want. Just you need to create the playlist first - or generate an ID that can be used if youre using uuids. You can still use a transaction/multi to ensure that the playlist creation worked before trying to create the videos.If you look at the docs for
cast_assocyou’ll see they all operate on something that wasRepo.get’d.Your changeset validations are run when called, so with that in mind it should make sense why the validation is failing.
leon_cruz
@soup thanks for you anwser!
I thought initially in this case, but if remove the validation on playlist_id on Video, the creation occours without errors and the video is linked to playlist. But, if create a video without a playlist_id a not null constrait exception is raised because there is not validation. How I setup for this case?
al2o3cr
cast_assoccombined withvalidate_requiredon the child schema’s foreign key will not work (see also a lot of the search results on this forum forcast_assoc). When you’re creating aPlaylist, the relatedVideochangesets need to be valid before thePlaylisthas an ID.My suggestion to resolve this:
use a changeset function in
cast_assoc(:videos, ...)that doesn’t cast or requireplaylist_id; that value will be set by the Ecto machinery automaticallyif a video cannot be created without a
playlist_id, enforce this at the database level with anull: falseconstraint on the columnA rule I find useful to help decide if something should be validated in a
changesetfunction: is there a meaningful way to give feedback about a resulting error to the user? For instance, a blanknameorcategorycan show a “can’t be blank” message next to the UI for that value - what feedback could a missingplaylist_idgive?LostKobrakai
If you indeed create videos standalone as well as part of a playlist then I’d suggest two changeset functions, one with
validate_requiredforplaylist_idand one without.soup
The error includes instructions,
or more generally
leon_cruz
i’ve already setup this
For this case, the message error will be like: “must be select a playlist”
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