如何在Elixir Struct中实现to_query(数据)

时间:2016-08-24 01:57:37

标签: elixir phoenix-framework ecto

我正在尝试使用Repo.update:

更新数据库中的现有记录
defmodule Oauth.EmailAddress do
  use Ecto.Model

  schema "email_address" do
    field :email_address, :string
    field :active, :boolean
    field :shop, :string
    field :verified, :boolean
    timestamps
  end
end

我有%Oauth.EmailAddress的模型:

** (Protocol.UndefinedError) protocol Ecto.Queryable not implemented   for %Oauth.EmailAddress

当我点击subscribe_email()时,会引发异常:

{{1}}

我知道我需要从Ecto.Queryable实现to_query()。但是,我不知道如何这样做。我不熟悉Elixir中的Protocols,虽然我已阅读官方文档,但我还没有使用Protocols。请解释如何为我的struct实现to_query()。

1 个答案:

答案 0 :(得分:2)

该错误有点误导。 Repo.all不接受带有像这样填充的字段的结构。你很有可能在寻找这个:

current_record =
  from(Oauth.EmailAddress)
  |> where(email_address: email_address, active: false, shop: shop, verified: :true)
  |> Repo.all

此外,由于您将结果传递给Ecto.Changeset.change,您可能只需要一条记录,而不是所有记录的列表:

current_record =
  from(Oauth.EmailAddress)
  |> where(email_address: email_address, active: false, shop: shop, verified: :true)
  |> Repo.one

请注意,如果查询有多个匹配记录,则会失败。