繁体   English   中英

在Elixir中使用Ecto,这无法评估现有索引的唯一约束

[英]Using Ecto in Elixir, this can't evaluate the unique contrant for an existing index

我有一个现有的数据库,并且该表中有一个唯一索引

ALTER TABLE ONLY users ADD CONSTRAINT unique_document_id UNIQUE (document_id);

我在Ecto中没有任何迁移,我想使用变更集插入新记录。 这是来自模型的代码和要插入的代码

defmodule User do
  use Ecto.Schema

  schema "users" do
    field :name
    field :email
    field :document_id
  end

  def signup(name, id_number, email) do
    changeset = User.changeset(%User{}, %{name: name,
                                            email: email,
                                            document_id: id_number})

    if changeset.valid? do
      IO.inspect "the chagenset is valid"
      user = case Repo.insert(changeset) do
        {:ok, model}        -> {:ok, model }
        {:error, changeset} -> {:error, changeset.errors}
      end
   end


def changeset(driver, params \\ :empty) do
    driver
    |> cast(params, [:document_id, :email, :name])
    |> validate_required([:document_id, :email, :name])
    |> unique_constraint(:document_id)
    |> unique_constraint(:email)
  end


  end

end

但是,当我尝试插入重复的用户时,出现此错误和changeset.valid吗? 是真的

11:04:17.896 [error] #PID<0.434.0> running App terminated
Server: localhost:4000 (http)
Request: POST /api/signup
** (exit) an exception was raised:
    ** (Ecto.ConstraintError) constraint error when attempting to insert struct:

    * unique: unique_document_id

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: users_document_id_index

        (ecto) lib/ecto/repo/schema.ex:493: anonymous fn/4 in Ecto.Repo.Schema.constraints_to_errors/3
        (elixir) lib/enum.ex:1229: Enum."-map/2-lists^map/1-0-"/2
        (ecto) lib/ecto/repo/schema.ex:479: Ecto.Repo.Schema.constraints_to_errors/3
        (ecto) lib/ecto/repo/schema.ex:213: anonymous fn/13 in Ecto.Repo.Schema.do_insert/4
        (ecto) lib/ecto/repo/schema.ex:684: anonymous fn/3 in Ecto.Repo.Schema.wrap_in_transaction/6
        (ecto) lib/ecto/adapters/sql.ex:620: anonymous fn/3 in Ecto.Adapters.SQL.do_transaction/3
        (db_connection) lib/db_connection.ex:1275: DBConnection.transaction_run/4
        (db_connection) lib/db_connection.ex:1199: DBConnection.run_begin/3

您需要在对unique_constraint的调用中指定约束名称,因为它不是默认的Ecto约定(如错误消息users_document_id_index ,它是users_document_id_index ):

|> unique_constraint(:document_id, name: :unique_document_id)

如果电子邮件也有唯一的约束名称,而不是users_name_index ,则也需要对unique_constraint(:name)进行相同的unique_constraint(:name)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM