如何在Elixir Struct中实现to_query(data) [英] How to implement to_query(data) in Elixir Struct
问题描述
我正在尝试使用Repo.update更新数据库中的现有记录:
I am attempting to update a existing records in my database using Repo.update:
def subscribe_email(conn, %{"email-address"=>email_address, "shop"=>shop}) do
current_record = Repo.all(%Oauth.EmailAddress{email_address: email_address, active: false, shop: shop, verified: :true})
current_record = Ecto.Changeset.change(current_record, active: :true)
case Repo.update current_record do
{:ok, struct} -> IO.puts "updated correctly."
{:error, changeset} -> IO.puts "did not update"
end
end
我有一个用于%Oauth.EmailAddress的模型:
I have a model for %Oauth.EmailAddress:
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
当我点击subscribe_email()时,会引发异常:
When I hit subscribe_email(), an exception is raised:
** (Protocol.UndefinedError) protocol Ecto.Queryable not implemented for %Oauth.EmailAddress
我知道我需要从Ecto.Queryable实现to_query().但是,我不知道如何做到这一点.尽管我已经阅读了官方文档,但是我还没有使用协议,所以我对Elixir中的协议不熟悉.请说明如何为我的结构实现to_query().
I know that I need to implement to_query() from Ecto.Queryable. However, I do not know how to do this. I am not familiar with Protocols in Elixir, although I have read the official documentation, I have not used Protocols. Please explain how to implement to_query() for my struct.
推荐答案
该错误有点令人误解. Repo.all
不接受这样填充字段的结构.您最有可能在寻找这个东西:
That error is a bit misleading. Repo.all
doesn't accept a struct with fields filled in like that. You're most likely looking for this:
current_record =
from(Oauth.EmailAddress)
|> where(email_address: email_address, active: false, shop: shop, verified: :true)
|> Repo.all
此外,由于您要将结果传递给Ecto.Changeset.change
,因此您可能只需要一个记录,而不是所有记录的列表:
Also, since you're passing the result to Ecto.Changeset.change
, you probably want just one record, not a list of all records:
current_record =
from(Oauth.EmailAddress)
|> where(email_address: email_address, active: false, shop: shop, verified: :true)
|> Repo.one
请注意,如果查询有多个匹配记录,则此操作将失败.
Note that this will fail if there's more than one matching record for the query.
这篇关于如何在Elixir Struct中实现to_query(data)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!