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