2017-05-09 47 views
0

我有一個現有的數據庫,並有一個唯一索引在表在藥劑使用外生,這不能評價的唯一contrant爲現有的指數

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

我沒有在任何外生遷移和我想使用變更集插入新記錄。下面是從模型和代碼的代碼中插入

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 

回答

3

你需要在調用unique_constraint指定約束名稱,因爲它不是默認的外生約定(這將是users_document_id_index,作爲錯誤消息說):

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

如果您對於電子郵件也有一個唯一的約束名稱,它不是users_name_index,您也需要對unique_constraint(:name)執行相同的操作。