Softknobs

Softknobs

How to update a belongs_to association?

Hi,

It looks like Ecto prevents, by default, to change an association because on_update is :raiseby default.

I naively changed my belongs_to association and added on_update: :update as suggested by the documentation but I now have another error:

Since you have set `:on_replace` to `:update`, you are only allowed
to update the existing entry by giving updated fields as a map or
keyword list or set it to nil.

If you indeed want to replace the existing :type, you have
to change the foreign key field directly.

I don’t really understand what that means because:
a) I pass my changes in a params parameter that is a map
b) it looks Ecto is suggesting me to change the value directly by specifying the database column, which sounds awkward.

So I tried the latter and set the TYP_ID column directly (ex: %{TYP_ID: 42}) with the new id. This did work but that means I need to reference database columns directly from my controller code, which looks to be a bad practice in my opinion.

What code do I need to change the id of an association in a table? This is how I expected it to be done but did not work:

Persitance:

  schema "upload" do
    field :filename, :string, source: :UPL_FILENAME, size: 500
    field :request_uuid, :string, source: :UPL_REQUEST_UUID, size: 100
    field :status_code, :string, source: :UPL_STATUS_CODE, size: 50
    belongs_to :type, Type, foreign_key: :TYP_ID, on_replace: :update
    timestamps()
  end

  def changeset(%{status_code: status_code} = upload, params \\ %{}) do
    upload
    |> change(params)
    |> cast(params, [:filename, :request_uuid, :status_code])
    |> validate_required([:filename])
    |> validate_required([:request_uuid])
    |> validate_required([:status_code])
  end
  
  def save_upload(%Upload{} = upload, params \\ %{}) do
    changeset(upload, params)
    |> Repo.insert_or_update()
  end

Insert or update:

    upload =
      Uploads.get_upload(String.to_integer(upload_id))
      |> Repo.preload(:type)
    updated_type = Uploads.get_type(new_type.id)
    Upload.save_upload(upload, %{type: updated_type})

This code works when I update the first time (when the column is null) but not on subsequent updates. How can I handle this case with Ecto?

Thanks.

Most Liked

thojanssens1

thojanssens1

Yes definitely. cast/4 creates a changeset from untrusted data (user input). You call change/2 for creating a changeset from trusted/internal data. You use either one or the other for transforming the params into a changeset. Here I suppose the parameters received are untrusted, so you just need to use cast/4. This doesn’t answer your question but that’s a first issue in the code:)

Where Next?

Popular in Questions Top

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
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
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
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31013 112
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36352 110
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement