Ecto unique pkey constraint error

I started getting the following error when trying to insert a new room

** (Ecto.ConstraintError) constraint error when attempting to insert struct:

    * unique: rooms_pkey

If you would like to convert this constraint into an error, please
call unique_constraint/3 in your changeset and define the proper
constraint name. The changeset defined the following constraints:

    * unique: rooms_name_index

Should auto-increment primary key? What can this error do suddenly? The insert is performed as part of a multi, with the corresponding part:

|> Multi.insert(:room, Room.changeset(%Room{}, %{name: "service-user-care-team:" <> Integer.to_string(user.id)}))

For further reference, here is my outline, including a set of changes

schema "rooms" do
  field :name, :string
  many_to_many :users, App.User, join_through: "user_rooms", on_delete: :delete_all
  has_many :messages, App.Message

  timestamps()
end

def changeset(struct, params \\ %{}) do
  struct
  |> cast(params, [:name])
  |> validate_required([:name])
  |> unique_constraint(:name)
end

And here is the migration

defmodule App.Repo.Migrations.CreateRoom do
  use Ecto.Migration

  def change do
    create table(:rooms) do
      add :name, :string, null: false

      timestamps()
    end

    create unique_index(:rooms, [:name])
 end
end
+4
source share
1 answer

I found why this is happening.

An important point that I forgot to include in the original description is that this happened while working in the dev environment.

. Postico, , , . pkey ​​ , .

0

Source: https://habr.com/ru/post/1686569/


All Articles