silverdr

silverdr

I have a one-to-many relation where I – say – add items to cart. Once I add one item it’s fine. When I add another I get:

errors: [id: {"has already been taken", []}]

on the second item, even if it’s not persisted. The whole changeset looks (simplified) like:

#Ecto.Changeset<
  action: :validate,
  changes: %{
    [...]
    items: [
      #Ecto.Changeset<
        action: :insert,
        changes: %{
          description: "gin",
          [...]
        },
        errors: [],
        data: #MyApp.Cart.Item<>,
        valid?: true
      >,
      #Ecto.Changeset<
        action: :insert,
        changes: %{
          description: "tonic",
          [...]
        },
        errors: [id: {"has already been taken", []}],
        data: #MyApp.Cart.Item<>,
        valid?: false
      >
    ],
  },
  errors: [],
  [...]
  valid?: false
>

I “put” the action “validate” on the parent in the changeset like:

changeset = %Cart{}
|> Cart.changeset(add_static_fields(params, socket))
|> Map.put(:action, :validate)

but apparently children have action “insert” in their respective changesets. Since I am not “inserting” the parent anyway, why do the children complain about their “id being taken”? No id’s been assigned yet, or what part of my brain is not working today?

Showing Posts 1 to 7

al2o3cr

al2o3cr

Can you show the code for Item.changeset? I’ve got several questions:

  • where are the Item changesets getting any value for id?
  • who is adding that error?
  • the DB-side uniqueness validations would need to somehow get ahold of an Ecto.Repo; is there anything unusual in Cart.changeset?
silverdr

silverdr OP

  • where are the Item changesets getting any value for id?

There’s no explicit assignment. DB sequence assigns it upon creating record. Here the record is not created and the ‘id’ is not in the changeset. OTOH the form does have an id field

  "items" => %{
    "0" => %{
      "description" => "gin",
      "id" => "",
      [...]
    },
    "1" => %{
      "description" => "tonic",
      "id" => "",
      [...]
    }

but values are empty there and as discussed in another thread there should be no need for “scrubbing” them. I might try doing this still manually and see if that helps

  • who is adding that error?

I take Ecto adds it. No explicit addition from the application’s code

  • the DB-side uniqueness validations would need to somehow get ahold of an Ecto.Repo; is there anything unusual in Cart.changeset?

I think Ecto adds it before DB has any chance of having a stab at checking. It looks to me like it sees the two (empty) ids and concludes they’re the same before going further: a) the parent record is not inserted, b) there’s no DB activity in the logs, and to answer the question there’s nothing uncommon in the Cart.changeset. Casting attrs, and casting association:

	|> cast_assoc(:items, required: true)

plus some validations but only on the cart data itself

Can you show the code for Item.changeset ?

Sure!

def changeset(%MyApp.Carts.Item{} = item, attrs) do
	item
	|> cast(attrs, [:description, :quantity])
	|> validate_length(:description, [min: 2, max: 30])
	|> validate_required([:description, :quantity])
	|> validate_number(:quantity, [greater_than_or_equal_to: 1, less_than_or_equal_to: 99])
end
silverdr

silverdr OP

Yes, removing ids from form data helps. Hmm… :thinking:

dodo

dodo

Just ran into this problem as well, shouldn’t cast remove any non-permitted params?

al2o3cr

al2o3cr

This error isn’t coming from the database, it’s from the internals of cast_assoc:

https://github.com/elixir-ecto/ecto/blob/3ee206b63c13272f0d7a5d48c37dbc1045f07ea0/lib/ecto/changeset/relation.ex#L386-L394

Two thoughts on what could be causing this:

  • that code relies on the value being passed in id params casting to nil if it’s empty. Integers definitely do that, but (for instance) plain strings would not. What type are your ID columns?
  • Changesets allow any value to be set into action, but depend on specific values like :insert for some behaviors. The original post was setting the action to :validate; does the same issue persist if the action is set to :insert?
silverdr

silverdr OP

At least in my case I still believe that Ecto does this (adds the error) before anything goes to the DB level. And before doing casts/whatever. Kinda soft-bug it seems

dodo

dodo

Hi, thank you for the quick reply!

I am using regular auto-incrementing integer ids (bigserial). I set the id of newly created items to -1 in the frontend to avoid nullable types, I just ended up not sending those in the request to fix the issue.

The action field is not set manually, I am using cast_assoc with a has_many relation and on_replace: :delete because the frontend always sends all associations. The error appeared when the action was :update on the root entity and :insert on the associated (has_many) entities, those were preloaded but empty before updating.

I understand that Ecto relies on the id for finding existing entities and proceed depending on the on_replace option, but I thought the id would just be ignored when it does not match any existing entity.

Now that I think about it I actually prefer the existing behavior, it seems safer than just ignoring invalid ids :slight_smile:.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
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
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

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
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews