10

尝试插入新房间时开始出现以下错误

** (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
4

2 回答 2

3

我找到了为什么会这样。

我忘记在原始描述中包含的一个重要说明是,这是在开发环境中工作时发生的。

它与这个答案有关。我之前使用 Postico 手动插入了一些数据,其中必须明确包含 id。pkey 序列当时没有更新,后来导致设置了重复的 id。

于 2018-02-19T11:23:37.637 回答
1

tl;博士

代替

|> unique_constraint(:name)

|> unique_constraint(:name, name: :rooms_pkey)

===============

unique_constraint并不像您期望的那样工作。

在您发布的示例中,原子:name被传递到 unique_constraint。引用文档:

默认情况下,约束名称是从表 + 字段中推断出来的。复杂情况下可能需要明确要求

这就是为什么:rooms_name_index即使实际索引是:rooms_pkey. 您必须显式地选择该:name选项以避免这种默认行为。

于 2018-10-31T16:51:22.437 回答