gpt4 book ai didi

elixir - Phoenix.HTML.Form 不会从变更集中获取错误

转载 作者:行者123 更新时间:2023-12-02 07:21:57 25 4
gpt4 key购买 nike

我有如下所示的模板代码:

<%= form_for @changeset, @action, fn f -> %>
<%= if Enum.any?(f.errors) do %>
<%= for {attr, message} <- f.errors do %>
<li><%= humanize(attr) %> <%= message %></li>
<% end %>
<% end %>
<% end %>

但即使变更集包含错误,也不会打印错误。这是检查的表单结构。请注意,错误列表是空的,即使它是从带有错误的变更集构建的。
%Phoenix.HTML.Form{data: %BlogPhoenix.Comment{__meta__: #Ecto.Schema.Metadata<:built, "comments">,
content: nil, id: nil, inserted_at: nil, name: nil, post_id: nil,
posts: #Ecto.Association.NotLoaded<association :posts is not loaded>,
updated_at: nil}, errors: [], hidden: [], id: "comment",
impl: Phoenix.HTML.FormData.Ecto.Changeset, index: nil, name: "comment",
options: [method: "post"],
params: %{"content" => nil, "name" => nil, "post_id" => "1"},
source: #Ecto.Changeset<action: nil, changes: %{},
errors: [name: {"can't be blank", [validation: :required]},
content: {"can't be blank", [validation: :required]}],
data: #BlogPhoenix.Comment<>, valid?: false>}

这里发生了什么?不应该填充此错误列表吗?

最佳答案

您的变更集的 :action 为零,这就是隐藏错误的原因( see source )。

Ecto.Changeset docs (在“变更集操作”标题下)指出:

For example, frameworks such as Phoenix uses the value of changeset.action to decide if errors should be shown or not on a given form.



上面的文档建议了这种方法:
changeset = User.changeset(%User{}, %{age: 42, email: "mary@example.com"})

# Since we don't plan to call Repo.insert/2 or similar, we
# need to mimic part of its behaviour, which is to check if
# the changeset is valid and set its action accordingly if not.
if changeset.valid? do
... success case ...
else
changeset = %{changeset | action: :insert} # action can be anything
... failure case ...
end

关于elixir - Phoenix.HTML.Form 不会从变更集中获取错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43452343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com