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

Sam*_*ies 2 elixir phoenix-framework

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

<%= 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 %>
Run Code Online (Sandbox Code Playgroud)

但即使更改集包含错误,也不会打印错误.这是检查的表单结构.请注意,即使错误列表是根据更改集生成的,但错误列表仍为空.

%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>}
Run Code Online (Sandbox Code Playgroud)

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

Alv*_*tam 7

你的变更集:动作是零,这是隐藏错误的原因(参见来源).

Ecto.Changeset文档(下简称"变更集操作"标题)指出:

例如,像Phoenix这样的框架使用changeset.action的值来决定是否应该在给定表单上显示错误.

上面的文档提出了这种方法:

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
Run Code Online (Sandbox Code Playgroud)