Is there any way to make cast_assoc
happy with just a list of associations?
Why does it have to be converted into a map first?
%{ 0 => %{},
1 => %{},
# ...
}
Is there any way to make cast_assoc
happy with just a list of associations?
Why does it have to be converted into a map first?
%{ 0 => %{},
1 => %{},
# ...
}
Does it have to be converted to a map first at all? Looking at the docs, they work with lists.
I think @aiwaiwa is asking about why cast_assoc
requires a changeset struct rather then that a list of associations.
If I interpreted that correctly, the reasoning would be that cast_assoc
is part of Ecto.Changeset
module, a bundle of functions generally intended to work in conjunction and operate on changeset structs, a pattern which allows for straightforward pipelines.
User
|> Repo.get!(id)
|> Repo.preload(:addresses) # Only required when updating data
|> Ecto.Changeset.cast(params, [])
|> Ecto.Changeset.cast_assoc(:addresses, with: &MyApp.Address.changeset/2)
|> Ecto.Changeset.validate_required([:name, :email])
|> Ecto.Changeset.validate_format(:email, ~r/@/)
|> ...
That said, I’d be curious to hear more about the scenario and intention that led to this question.
@codeanpeace I’ll elaborate more. Thank you for tuning in!
I can’t do Repo.preload
, because it’s in the middle of an Multi, and while an error is happening due to another validation, and before actual saving of the associations, which are many_to_many
by the way.
I guess I need to provide even more details!