bohdan-shulha

bohdan-shulha

Using belongs_to in an embedded schema to create new records

Hi there.

I have another problem which I can’t fight on myself.

I have a deeply nested schema in my Ecto model. One of the deep inside branches looks like this:

embeds_many :configs, ConfigSpec, on_replace: :delete do
  def changeset(config_spec, attrs) do
    config_spec
    |> cast(attrs, [:target])
    |> cast_assoc(:config,
      required: true,
      with: &PtahServer.DockerConfigs.DockerConfig.changeset/2
    )
    |> validate_required([:target])
  end

  field :target, :string

  belongs_to :config, PtahServer.DockerConfigs.DockerConfig
end

Everything works fine until I want to add a new ConfigSpec.

I have been using the hidden inputs approach with the :configs_sort field, but whenever I click “add an item” I’m getting non-loaded association error on the :config field.

It works perfectly fine if database already has some data (I preload everything what’s required), fails only for items being created at the moment.

** (ArgumentError) using inputs_for for association `config` from `PtahServer.Services.Service.ServiceSpec.TaskTemplate.ContainerSpec.ConfigSpec` but it was not loaded. Please preload your associations before using them in inputs_for

What will be the right approach here?

Form is really deeply nested. :slightly_smiling_face:

stack[services][0][spec][task_template][container_spec][configs][0][config]

stack[services] is the list of Ecto models, whereas spec and everything inside (except the config field) are embedded schemas.

For the record, here is my PR: feat: #86 add support for custom tls certs by bohdan-shulha · Pull Request #87 · ptah-sh/ptah_server · GitHub

The related code belongs to lib/ptah_server_web/live/stack_live/components/service_component.html.heex

I have tried to manually override values in the changeset, but no luck - embedded records can be created, but the entity defined via belongs_to is not created.

First Post!

sodapopcan

sodapopcan

You need to build an empty association for every new one you want. For example:

defmodule Bar do
  schema "bars" do
    belongs_to :foo, Foo
  end
end

defmodule Foo do
  schema "foos" do
    has_many :bars, Bar
  end

  def append_empty_bar(changeset) do
    new_bar = %Bar{}
    current_bars = Ecto.Changeset.get_assoc(changeset, :bars) # in your case, `get_embed`
    updated_bars = current_bars ++ [new_bar]

    Ecto.Changeset.put_assoc(:bars, updated_bars) # or in your case, `put_embed`
  end
end

# In some context function:
changeset =
  Foo.changeset()
  |> Foo.append_new_bar()

I wouldn’t necessarily call this exemplary code, I just wanted to make it as clear as I could (apologies if I failed here).

You should take a look at this lib: ecto_nested_changeset.

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New

We're in Beta

About us Mission Statement