尝试插入新房间时出现以下错误
** (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
主键不应该自增吗?什么会导致这个错误突然发生?插入是作为 multi 的一部分完成的,相关部分是:
|> Multi.insert(:room, Room.changeset(%Room{}, %{name: "service-user-care-team:" <> Integer.to_string(user.id)}))
作为额外引用,这是我的架构,包括变更集
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
这是迁移
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
最佳答案
我找到了发生这种情况的原因。
我忘记在原始描述中包含的重要说明是,这是在开发环境中工作时发生的。
与this answer有关.我之前用 Postico 手动插入了一些数据,其中必须明确包含 id。 pkey 序列在那一点上没有更新,后来导致设置了重复的 id。
关于postgresql - pkey 上的 Ecto 唯一约束错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46475815/