完成此迁移,以获得帐号
的唯一索引 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
Ecto 2.1.4
我错过了什么?
答案 0 :(得分:0)
您当前的代码正在使用
Ecto.Changeset.unique_constraint/2
错误说您应该使用Ecto.Changeset.unique_constraint/3
,这意味着您必须添加选项。在这种情况下,只需使用message
选项密钥
更改
|>unique_constraint(:account_number)
到
|>unique_constraint(:account_number, message: "Account number must be unique or some message like that")
答案 1 :(得分:0)
可能是因为您尝试插入现有的:account号码而发生的。 有两种解决方法:
unique_constraint
,并在数据库中创建非唯一索引,如下所示: def change do
drop unique_index(:users, [:account_number])
create index(:users, [:account_number])
end