arunkarottu
cast_assoc doesn’t seem to work when I create or update with an existing item in the many_to_many relationship and the item has a required field. See below for example:
defmodule EctoTest.Repo.Migrations.AddTodoListsAndItems do
use Ecto.Migration
def change do
create table("todo_lists") do
add(:title, :string, null: false)
timestamps()
end
create table("todo_items") do
add(:description, :string, null: false)
timestamps()
end
create table("todo_lists_items", primary_key: false) do
add(:todo_item_id, references(:todo_items), null: true)
add(:todo_list_id, references(:todo_lists), null: true)
end
end
end
defmodule EctoTest.Todos.TodoList do
use Ecto.Schema
alias Ecto.Changeset
alias EctoTest.Todos.TodoItem
schema "todo_lists" do
field :title
many_to_many :todo_items, TodoItem, join_through: "todo_lists_items", on_replace: :delete
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> Changeset.cast(params, [:title])
|> Changeset.cast_assoc(:todo_items, required: true)
end
end
defmodule EctoTest.Todos.TodoItem do
use Ecto.Schema
alias Ecto.Changeset
schema "todo_items" do
field :description
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> Changeset.cast(params, [:description])
|> Changeset.validate_required([:description])
end
end
defmodule EctoTest.Todos do
alias EctoTest.Repo
alias EctoTest.Todos.TodoItem
alias EctoTest.Todos.TodoList
def create_todo_item(attrs \\ %{}) do
%TodoItem{}
|> TodoItem.changeset(attrs)
|> Repo.insert()
end
def create_todo_list(attrs \\ %{}) do
%TodoList{}
|> TodoList.changeset(attrs)
|> Repo.insert()
end
def update_todo_list(%TodoList{} = todo_list, attrs \\ %{}) do
todo_list
|> Repo.preload([:todo_items])
|> TodoList.changeset(attrs)
|> Repo.update()
end
end
Both the following tests fail with similar errors
defmodule EctoTest.Todos.TodoListTest do
use EctoTest.DataCase
alias EctoTest.Todos
describe "create_todo_list/2" do
test "creates todo_list and casts todo_items" do
{:ok, todo_item} = Todos.create_todo_item(%{description: "Test description"})
todo_list_params = %{title: "Test title", todo_items: [%{id: todo_item.id}]}
assert {:ok, todo_list} = Todos.create_todo_list(todo_list_params)
end
end
describe "update_todo_list/2" do
test "updates todo_list and casts todo_items" do
{:ok, todo_item} = Todos.create_todo_item(%{description: "Test description"})
todo_list_params = %{title: "Test title", todo_items: [%{id: todo_item.id}]}
assert {:ok, todo_list} = Todos.create_todo_list(todo_list_params)
{:ok, new_todo_item} = Todos.create_todo_item(%{description: "New todo item"})
todo_list_params = %{todo_items: [%{id: new_todo_item.id}]}
assert {:ok, todo_list} = Todos.update_todo_list(todo_list, todo_list_params)
end
end
end
These are the errors I get
1) test update_todo_list/2 updates todo_list and casts todo_items (EctoTest.Todos.TodoListTest)
test/ecto_test/todos/todo_list_test.exs:15
match (=) failed
code: assert {:ok, todo_list} = Todos.create_todo_list(todo_list_params)
right: {:error,
#Ecto.Changeset<
action: :insert,
changes: %{
title: "Test title",
todo_items: [
#Ecto.Changeset<
action: :insert,
changes: %{},
errors: [
description: {"can't be blank", [validation: :required]}
],
data: #EctoTest.Todos.TodoItem<>,
valid?: false
>
]
},
errors: [],
data: #EctoTest.Todos.TodoList<>,
valid?: false
>}
stacktrace:
test/ecto_test/todos/todo_list_test.exs:19: (test)
2) test create_todo_list/2 creates todo_list and casts todo_items (EctoTest.Todos.TodoListTest)
test/ecto_test/todos/todo_list_test.exs:6
match (=) failed
code: assert {:ok, todo_list} = Todos.create_todo_list(todo_list_params)
right: {:error,
#Ecto.Changeset<
action: :insert,
changes: %{
title: "Test title",
todo_items: [
#Ecto.Changeset<
action: :insert,
changes: %{},
errors: [
description: {"can't be blank", [validation: :required]}
],
data: #EctoTest.Todos.TodoItem<>,
valid?: false
>
]
},
errors: [],
data: #EctoTest.Todos.TodoList<>,
valid?: false
>}
stacktrace:
test/ecto_test/todos/todo_list_test.exs:10: (test)
Is this expected behavior? If so, what’s the best way for me to make this work?
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hi everyone,
I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding.
I sta...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
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
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New
Other Trending Topics
Edit: 2026 May 15 - This post is archived.
Mob is alive!!
Main docs: mob v0.7.11 — Documentation
A bit of explanation for the slightly c...
New
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
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
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #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
- #ai
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #elixirconf-eu
- #metaprogramming
- #hex










Showing Posts 1 to 6- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
joaquinalcerro
Please check out this example. I am currently in my mobile device:
Please let me know if it helped.
Best regards,
jeremyjh
We don’t run into this problem with
has_manyassociations, it seems unique tomany_to_many.joaquinalcerro
So, just to get the error out out the way, they are because the TodoItem changeset has a required field :description
… and you are calling it with just the “id”
But even if you fix that, you are still going to run into trouble. cast_assoc requires you to handle both parent and child association at once. You should have a params structure similar to:
Please note that in your test, you are first saving the TodoItem and then adding it to a TodoList and this will not work because cast_assoc works with both at one.
Your actual TodoList.changeset should work when you are creating the record but if you are updating it you have preload the TodoItem association first.
You can also reference the documentation for cast_assoc:
Hope this helps. Best regards,
jeremyjh
He’s calling it with just the
id, because there is already a description in the record. Since he preloads that association, we’re expecting a preloaded struct to be passed to the changeset like we’d have in ahas_manyrelationship, but that is not happening.On the update, it is preloaded:
joaquinalcerro
Oh,
Focusing only on the changeset errors:
As you can see in the errors, the function that is been called is the Todos.create_todo_list(todo_list_params) so there is no preload inside this function.
Looks like the code is ok but not the test code.
So, if I wanted to test the creation of the parent and child at the same time with none of them existing, I would try the following code as my test
Creating a new todo_list with a existing todo_item is not possible because you can’t preload a child associations of a non existing parent.
Hope this clarifies what I was trying to explain.
Best regards,
jeremyjh
Yes I agree the create can’t work the way he has it. What about the update though? Shouldn’t the preloaded struct be passed to changeset function?