我正在尝试创建一个基本的 CRUD 应用程序,但我遇到了验证问题。这是我的控制器动作:
def update(conn, %{"id" => id, "user" => params}) do
case Repo.get(User, String.to_integer(id)) do
user when is_map(user) ->
user = Map.merge(user, atomize_keys(params))
case User.validate(user) do
[] ->
Repo.update(user)
redirect conn, to: user_path(:show, user.id)
errors ->
text conn, "Validation Failed!"
##render conn, "editform.html", user: user, errors: errors
end
_ ->
redirect conn, to: user_path(:index)
end
end
和我的模型:
defmodule MyApp.User do
use Ecto.Model
validate user,
email: present()
schema "users" do
field :first_name, :string
field :last_name, :string
field :email, :string
field :created_at, :datetime, default: Ecto.DateTime.local
field :updated_at, :datetime, default: Ecto.DateTime.local
end
end
User.validate(user) 似乎返回了一些东西,但不是错误 - form.html 中没有显示错误。我在这里想念什么?这可能是 atomize_keys() 函数的问题吗?这是那个:
defp atomize_keys(struct) do
Enum.reduce struct, %{}, fn({k, v}, map)
-> Map.put(map, String.to_atom(k), v) end
end