当尝试构建表单验证时,当我使用超过 20 个字符的用户名时,我的错误出现在表单中,但当我什么都不输入时却没有。我得到一个 violates non-null constraint Postgres.Error View 。
# user.ex
def changeset(model, params \\ %{}) do
model
|> cast(params, ~w(name username), [])
|> validate_length(:username, min: 1, max: 20)
end
这可能是因为迁移:
def change do
create table(:users) do
add :name, :string
add :username, :string, null: false
add :password_hash, :string
timestamps
end
create unique_index(:users, [:username])
end
通过 Programming Phoenix 这本书,不幸的是它有点过时了,我找不到快速解决这个问题的方法。
不知何故,Postgres 不应该出现在验证检查之前。关于如何消除此错误的任何想法?
最佳答案
如果它不起作用,我假设你使用的是 Phoenix 1.3,所以尝试更改此代码
def changeset(model, params \\ %{}) do
model
|> cast(params, ~w(name username), [])
|> validate_length(:username, min: 1, max: 20)
end
有了这个:
def changeset(model, params \\ %{}) do
model
|> cast(params, ~w(name username))
|> validate_required([:username])
|> validate_length(:username, min: 1, max: 20)
end
您可以在 Ecto.Changeset.validate_required/3
的文档中查看更多详细信息.
希望对您有所帮助!
关于postgresql - Phoenix 表单验证检查未显示,但来自 postgres 的非空约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48085798/