【问题标题】:Protocol Enumerable not implemented for MyApp.MyStruct未为 MyApp.MyStruct 实现协议可枚举
【发布时间】:2018-05-22 05:00:53
【问题描述】:

我正在尝试创建一个连接表,并且在尝试构建一个结构时遇到了这个错误。

错误

protocol Enumerable 未为 %Statcasters.UsersLeagues{meta 实现:#Ecto.Schema.Metadata<:built>,专员:nil,id:nil,inserted_at:nil,league :#Ecto.Association.NotLoaded,league_id:nil,updated_at:nil,用户:#Ecto.Association.NotLoaded,user_id:nil}。该协议适用于:DBConnection.PrepareStream、DBConnection.Stream、Date.Range、Ecto.Adapters.SQL.Stream、File.Stream、Function、GenEvent.Stream、HashDict、HashSet、IO.Stream、List、Map、MapSet、 Postgrex.Stream, Range, Stream, Timex.Interval

这条线失败了:

联赛控制器:

  def new(conn, _params) do
    changeset = League.changeset(%League{users_leagues: %UsersLeagues{}})

    render(conn, "new.html", changeset: changeset)
  end

我与联盟和用户建立了 has_many 关系。连接表是 users_leages 表,这就是我试图在新操作中创建的。但是当我尝试加载新页面时。它因这个错误而中断。

【问题讨论】:

  • 尝试将%UsersLeagues{} 更改为[%UsersLeagues{}]
  • 成功了!但我不明白为什么?

标签: elixir phoenix-framework


【解决方案1】:

该错误意味着 Ecto 试图将字段 users_leagues 的值用作 Enumerable,而 %UsersLeagues{} 不是。由于该字段是 has_many 字段,因此一条记录可以包含多个字段,并且它需要是 %UsersLeagues{} 结构的列表(或更具体地说是一个 Enumerable)。

您可以通过将%UsersLeagues{} 包装在一个列表中来解决此问题:

changeset = League.changeset(%League{users_leagues: [%UsersLeagues{}]})

【讨论】:

    猜你喜欢
    • 2016-05-09
    • 2016-04-26
    • 2018-07-28
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2017-12-19
    相关资源
    最近更新 更多