Why does this code fail with Ecto.NoPrimaryKeyValueError

1.4k Views Asked by At

Why does this fail:

%Partner{} |> cast(%{id: 123}, [:id]) |> delete 

with a Ecto.NoPrimaryKeyValueError? I'm setting the primary key explicitly?

1

There are 1 best solutions below

1
On BEST ANSWER

For changesets, the id from the original struct (data) is used by Repo.delete, and not the one in changes, and cast puts the new id only in changes. You can either merge changes into the original struct (data):

%Partner{} |> cast(%{id: 123}, [:id]) |> Ecto.Changeset.apply_changes |> delete 

or put the id into %Partner{} manually:

%Partner{id: 123} |> delete