【问题标题】:Elixir Ecto where Query Throwing `Protocol not implemented Error`Elixir Ecto where Query Throwing `Protocol not implemented Error`
【发布时间】:2019-03-16 16:35:37
【问题描述】:

我认为 Elixir 中有一个相对简单的 Ecto 查询,它抛出一个错误“协议未实现”,我很困惑为什么。

所以这里是查询:

    head_children_list =    Comments
                                |> where([c], c.inserted_at in ^head_children) 
                                |> Enum.sort_by(& &1["votetotal"])

所以 head_children 是一个包含一个字符串时间戳值的列表。这是确认的终端输出:

value of head_children
["2018-10-11 14:08:15.021033"]

所以我知道一个事实,这是一个列表。但是,当我尝试执行上述查询时,我得到以下信息:

[info] Sent 500 in 168ms
[error] #PID<0.401.0> running AlbatrossWeb.Endpoint (cowboy_protocol) terminated
Server: localhost:4000 (http)
Request: POST /voteComment
** (exit) an exception was raised:
    ** (Protocol.UndefinedError) protocol Enumerable not implemented for #Ecto.Query<from c in Albatross.Comments, where: c.inserted_at in ^[["2018-10-11 14:08:15.021033"]]>. This protocol is implemented for: 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

请注意,这表示为列表实现了协议。但这是一个清单!所以我很困惑。我试过使用^[head_children],它只是将它包装在另一个列表中,但这也失败并出现同样的错误。

有人知道怎么回事吗?

【问题讨论】:

  • 旁注:最好在数据库中排序。

标签: postgresql list elixir phoenix-framework ecto


【解决方案1】:

where(Comments, [c], c.inserted_at in ^head_children) 返回一个%Ecto.Query{},它通过管道传递到Enum.sort_by/2%Ecto.Query{} 是一个结构而不是一个列表,它不是Enumerable

你可能想要

head_children_list =
  Comments
  |> where([c], c.inserted_at in ^head_children)
  |> Repo.all()
  |> Enum.sort_by(& &1["votetotal"])

【讨论】:

  • 我会给你答案,因为这也是一个问题。我真正的问题是我试图将时间戳()用作字段(即插入的_at),这是不行的。谢谢!
猜你喜欢
  • 2018-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多