【问题标题】:Phoenix form validation check not showing up but non-null constraint from postgresPhoenix 表单验证检查未显示,但来自 postgres 的非空约束
【发布时间】:2018-01-04 06:41:47
【问题描述】:

在尝试构建表单验证时,当我使用超过 20 个字符的用户名时,我的错误会显示在表单中,但当我什么都不输入时不会。我得到一个违反非空约束 Postgres.Error 视图。

# 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 不应该在验证检查之前出现。关于如何消除此错误的任何想法?

【问题讨论】:

  • 您是否尝试将validate_required([:username, :other_fields]) 添加到您的变更集管道中?

标签: postgresql elixir phoenix-framework


【解决方案1】:

如果不起作用,我假设您使用的是 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的文档中查看更多详细信息。

希望有帮助!

【讨论】:

  • 我只是在写基本上完全一样的东西?
  • 这确实可以解决问题,我必须有点细致,并注意现在我(当然)得到“不能空白”,而书中显示更合适的“应该至少 1 个字符”也是可能的。 min: 部分只是以某种方式错过了它的功能。
  • 当然不同,我想我可以保留额外的代码行。
猜你喜欢
  • 2010-11-13
  • 1970-01-01
  • 2022-11-19
  • 2020-09-03
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多