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

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
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
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
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
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

Other popular topics Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
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
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 record...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
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
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement