2017-08-24 96 views
0

雖然我所說的unique_constraint/3在變更爲:爲什麼我會得到Ecto.ConstraintError?

def changeset(parent, params \\ %{}) do 
    parent 
    |> cast(params, [:created_at , :parent_type , :mobile_number]) 
    |> unique_constraint(:mobile_number, name: :parents_mobile_number_uindex) 

    end 

我仍然得到錯誤,當我做Repo.update!Repo.update

** (exit) an exception was raised: 
    ** (Ecto.ConstraintError) constraint error when attempting to update struct: 

    * unique: parents_mobile_number_uindex 

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 has not defined any constraint. 

     (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:284: anonymous fn/13 in Ecto.Repo.Schema.do_update/4 
     (ecto) lib/ecto/repo/schema.ex:142: Ecto.Repo.Schema.update!/4 
     (myapp) web/controllers/csvs_controller.ex:484: Myapp.CsvsController.parent_insert_or_update/2 
     (myapp) web/controllers/csvs_controller.ex:266: anonymous fn/6 in Myapp.CsvsController.write_ecto_rows_schools/6 
     (myapp) web/controllers/csvs_controller.ex:219: Myapp.CsvsController.write_ecto_rows_schools/6 
     (elixir) lib/task/supervised.ex:85: Task.Supervised.do_apply/2 
     (elixir) lib/task/supervised.ex:36: Task.Supervised.reply/5 
     (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3 

任何想法?

編輯:

我已經在數據庫約束: enter image description here

EDIT2: enter image description here

回答

0

Ecto.ConstraintError發生很可能是由於基於不正確的約束名你的錯誤信息。 「」變更集沒有定義任何約束。「

您將明確的索引名稱傳遞給unique_constraint。所以,外生將查找唯一索引 「parents_mobile_number_uindex」

create unique_index(:parents, [:mobile_number]) 
# geneated a unique index "parents_mobile_number_index" 

兩件事情來看待:

  1. 確保唯一索引的名字是正確的:

    ## at your migration file 
    create unique_index(:parents, [:mobile_number], name: : parents_mobile_number_uindex) 
    
    ## at your schema module. 
    def changeset(parent, params \\ %{}) do 
        parent 
        |> cast(params, [:created_at , :parent_type , :mobile_number]) 
        |> unique_constraint(:mobile_number, name: : parents_mobile_number_uindex) 
    end 
    
  2. 確保您確實稱之爲unique_constraint/3功能:

    parent |> Parent.changeset(%{mobile_number: parent_model.mobile_number}) |> Repo.update() 
    # or 
    parent |> Ecto.Changeset.change(mobile_number: parent_model.mobile_number) |> unique_constraint(:mobile_number, name: :parents_mobile_number_uindex) |> Repo.update() 
    
+0

謝謝,但已經在DB的約束,請檢查編輯上面 – simo

+0

有趣。你能告訴我「web/controllers/csvs_controller.ex:484」的代碼 – jccf091

+0

請檢查EDIT2上面 – simo

相關問題