Hi
I had this piece of (working) code:
items =
products
|> Enum.map(fn product ->
params = %{product_id: product.id}
Snapshot.new_item_changeset(
%Snapshot.Item{
product: product
},
params
)
end)
That later created a form with:
form =
Ecto.Changeset.put_embed(
Ecto.Changeset.change(%Snapshot{}),
:items,
items
)
|> to_form
That I was rendering as:
<.form for={@form} phx-change="validate" phx-submit="save">
<.inputs_for :let={snapshot} field={@form[:items]}>
<div><%= snapshot.data.product.description %></div>
However, since I didn’t want to repeat that Ecto.Changeset.put_embed(
I wanted to move that logic to the schema as:
def changeset(snapshot, params \\ %{}) do
snapshot
|> cast(params, [])
|> cast_embed(:items, with: &new_item_changeset/2)
end
def new_item_changeset(item, params \\ %{}) do
item
|> cast(params, [:quantity, :product_id, :rate_id])
|> validate_number(:quantity, greater_than_or_equal_to: 0)
end
But if I move the original code to:
items =
products
|> Enum.map(fn product ->
%{product_id: product.id}
end)
And then just:
form =
Snapshot.changeset(%Snapshot{}, %{items: items})
|> to_form
That works, however the template doesn’t have a product
loaded ending up in the following error:
key :description not found in: #Ecto.Association.NotLoaded<association :product is not loaded>
It would be easy to fix this with a Repo.preload
but since it’s an embedded schema I am not sure where to do that.