agonzalezro

agonzalezro

Hi :wave:

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.

Showing Posts 1 to 6

i-n-g-m-a-r

i-n-g-m-a-r

So first you assigned a product and later you only assigned an ID and then you lost the product?

agonzalezro

agonzalezro OP

Thanks for your reply @i-n-g-m-a-r,

when you say that I “assigned” something you mean that I have a list of products and I just map it to get the product.id?

I was doing it like that because in the past I was using the product when creating the Snapshot.Item{} (you can see that in the first snippet), however, now that I want to use Snapshot.changeset to create the embedded version I don’t know how to set it or preload it.

i-n-g-m-a-r

i-n-g-m-a-r

I mean assigning a value to a variable, like so: product: product.
Before you were loading product data into a changeset.
Now you seem to disregard everything but the product ID.
So it makes sense you would end up with an ID only.
Changesets don’t do any (pre)loading.
Their function is to guarantee valid data.

agonzalezro

agonzalezro OP

Thanks again for your response @i-n-g-m-a-r.

What do you think would be the best approach to solve this issue then? Should I send a products map to the template and use the changeset product_id to read the product info from the map?

It seems there are ways to solve this, I am just not sure what would be the “most correct” (if that even exists :sweat_smile:) in Phoenix’s world. I thought that even when the changeset wouldn’t take the product into consideration and just use the product_id relation that was the proper way to do it.

Any insight would be welcome!

i-n-g-m-a-r

i-n-g-m-a-r

Actually when I started using ecto it was not easy for me to fully grasp the power of changesets.
The concept is very powerful, you just need some experience to “get it”.

I’m not the right guy to ask about “correctness”.
Personally I use a macro to build schema’s automatically inserting changeset functions and all kinds of pre and post data transformation hooks.
I don’t think anyone considers that to be “correct”.

I think this part is a good starting point:
Snapshot.changeset(%Snapshot{}, %{items: items})

I would focus first on fetching items.
Making sure every item is a certain struct.
Validated using changesets.

Then when you want to load a list of structs into a list of another type of structs, you can first (recursively) transform the list into a list of “params” (a nested map) and then load the params into a changeset for every item.
This should “just” work, no need for put_embed.

Also when you have a list of structs, you could load them into a schema embedding a list of structs (embeds_many).
Then you would have a (guaranteed) “type” instead of (just) a list.
In order to embed schema’s that are stored as records in a database you can create schemaless “meta” models.
I do this all the time.
Repo.all |> to_meta |> to_form
Submit…
params |> to_meta |> validate |> to_schema |> Repo.update_all

I would want my interface to look like this:
Snapshot.changeset(params)

Or like this:
Snapshot.changeset(stored_struct, params)

agonzalezro

agonzalezro OP

Thanks for the proposals.

I finally fixed my initial issue by also assigning to the socket a map of product id to product:

%{"1" => %xxx.Products.Product{

Then on the form I am showing it as follows:

<div><%= @products[snapshot.params["product_id"] |> to_string].description %></div>
— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
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
velrest
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
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
mnkhod
So i have been using ash framework for a while and i love it. However currently the issue im having with ash framework is the error handl...
New

Other Trending Topics Top

GenericJam
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
JesseHerrick
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
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews