Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Validation Phoenix Exto唯一验证:尝试插入结构时出现约束错误_Validation_Elixir_Phoenix Framework_Ecto - Fatal编程技术网

Validation Phoenix Exto唯一验证:尝试插入结构时出现约束错误

Validation Phoenix Exto唯一验证:尝试插入结构时出现约束错误,validation,elixir,phoenix-framework,ecto,Validation,Elixir,Phoenix Framework,Ecto,运行此迁移以便在帐号上具有唯一索引 def change do create unique_index(:users, [:account_number]) end 然后在模型中: def changeset(struct, params \\ %{}) do struct |> cast(params, [:first_name, :last_name, :email, :phone, :city, :postal_code, :country, :lo

运行此迁移以便在帐号上具有唯一索引

  def change do
    create unique_index(:users, [:account_number])
  end
然后在模型中:

def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:first_name, :last_name, :email, :phone, :city, :postal_code, :country, :login_count, :last_login, :active, :account_number, :password])
    |> validate_required([:first_name, :last_name, :email, :phone, :city, :postal_code, :country, :account_number])
    |> validate_length(:password, min: 8, max: 100)
    |> validate_format(:email, ~r/@/)
    |> unique_constraint(:email)
    |> unique_constraint(:account_number)
    |> put_pass_hash()
  end
产生以下错误:

 ** (Ecto.ConstraintError) constraint error when attempting to insert struct:

     * unique: users_account_number_index

 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.
PostgreSQL 9.6
凤凰城1.2.4
外星2.1.4


我缺少什么?

您当前的代码正在使用
exto.Changeset.unique\u约束/2
错误提示您应该使用
exto.Changeset.unique\u constraint/3
,这意味着您必须添加选项。在这种情况下,只需使用
message
选项键添加约束错误消息即可

改变

|>唯一约束(:帐号)


|>唯一约束(:account\u number,message:“account number必须是唯一的或类似的消息”)

可能会发生这种情况,因为您尝试插入现有的:account number。 有两种方法可以解决此问题:

  • 如果需要保持这些字段的唯一性,请确保插入唯一字段
  • 否则,您可以从模式中删除
    unique\u约束
    ,并在数据库中创建非唯一索引,如下所示:

  • 变更集没有定义任何约束。
    很奇怪。您是否确定此
    变更集
    函数位于
    用户
    模型中,并且您正在插入此函数返回的变更集?并且编译的所有内容都正确无误?
      def change do
        drop unique_index(:users, [:account_number])
        create index(:users, [:account_number])
      end