未为结构实现协议枚举。如何将结构转换为可枚举的?

Ole*_*ann 2 erlang elixir phoenix-framework

我正在使用结构在 Phoenix/Elixir 应用程序中创建自定义模型。像这样:

defmodule MyApp.User do
  defstruct username: nil, email: nil, password: nil, hashed_password: nil
end

new_user = %MyApp.User{email: "email@example.com", hashed_password: nil, password: "secret", username: "ole"}
Run Code Online (Sandbox Code Playgroud)

为了将它与我的数据库适配器一起使用,我需要数据是可枚举的。结构显然不是。至少我收到这个错误:

(Protocol.UndefinedError) protocol Enumerable not implemented for %MyApp.User{ ...
Run Code Online (Sandbox Code Playgroud)

所以我尝试使用理解来碰运气。这当然也不起作用,因为结构不可枚举(愚蠢的我)

enumberable_user = for {key, val} <- new_user, into: %{}, do: {key, val}
Run Code Online (Sandbox Code Playgroud)

如何将数据转换为可枚举的地图?

Gaz*_*ler 5

您可以使用Map.from_struct/1在插入数据库时​​将其转换为映射。这将删除__struct__密钥。

你曾经可以派生出 Enumerable 协议,但似乎是偶然的。https://github.com/elixir-lang/elixir/issues/3821

哎呀,以前派生工作是偶然的,我认为我们不应该修复它。也许我们可以更新 v1.1 更改日志以使其清楚,但我不会更改代码。

defmodule User do
  @derive [Enumerable]
  defstruct name: "", age: 0
end

Enum.each %User{name: "jose"}, fn {k, v} ->
  IO.puts "Got #{k}: #{v}"
end
Run Code Online (Sandbox Code Playgroud)