gpt4 book ai didi

elixir - 如何在 Ecto 模型中使用 uuid

转载 作者:行者123 更新时间:2023-12-01 12:37:47 25 4
gpt4 key购买 nike

我正在尝试将 uuid 与 ecto 一起使用。我可以查询所有内容,但我在 Repo.get 中遇到了 unable to encode value 错误。

defmodule Rocket.Model do
defmacro __using__(_) do
quote do
use Ecto.Model
@primary_key {:id, :uuid, []}
@foreign_key_type :uuid
end
end
end

defmodule Rocket.User do
use Rocket.Model

schema "users" do
field :created_at, :datetime
field :name, :string
field :email, :string
field :password, :string
field :timezone, :string
end
end


iex(37)> Rocket.Repo.get(Rocket.User,"00000000-0000-0000-0000-00000000011b")
21:51:58.291 [debug] SELECT u0."id", u0."created_at", u0."name", u0."email", u0."password", u0."timezone" FROM "users" AS u0 WHERE (u0."id" = $1) (0.4ms)
** (Postgrex.Error) unable to encode value `"00000000-0000-0000-0000-00000000011b"` as type uuid
(ecto) lib/ecto/adapters/sql/worker.ex:18: Ecto.Adapters.SQL.Worker.query!/4
(ecto) lib/ecto/adapters/sql.ex:186: Ecto.Adapters.SQL.use_worker/3
(rocket) web/models/repo.ex:2: Rocket.Repo.log/2
(ecto) lib/ecto/adapters/sql.ex:315: Ecto.Adapters.SQL.all/5
(ecto) lib/ecto/repo/queryable.ex:20: Ecto.Repo.Queryable.all/4
(ecto) lib/ecto/repo/queryable.ex:43: Ecto.Repo.Queryable.one/4
iex(37)>

使用所有功能,但 uuid 在控制台或 json 解码中均未表示为字符串:

iex(38)> user = Rocket.Repo.all(Rocket.User) |> List.first
21:58:55.450 [debug] SELECT u0."id", u0."created_at", u0."name", u0."email", u0."password", u0."timezone" FROM "users" AS u0 (1.5ms)
%Rocket.User{created_at: %Ecto.DateTime{day: 3, hour: 2, min: 16, month: 1,
sec: 3, year: 2015}, email: "joel@foo.com",
id: <<0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 29>>, name: "Joel",
password: "$1$E0eFWgDt$YgQTEByVT7prYkT2IqBjL1", timezone: nil}
iex(39)> IO.puts Poison.Encoder.encode(udb,[])
{"timezone":null,"password":"$1$E0eFWgDt$YgQTEByVT7prYkT2IqBjL1","name":"Joel","id":"\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0001\u001D","email":"joel@foo.com","created_at":{"year":2015,"sec":3,"month":1,"min":16,"hour":2,"day":3}}
:ok

最佳答案

UUID 只有 16 个字节,所以你从 all/1 得到的实际上是正确的。如果您想使用 UUID 的详细表示,您可以显式转换它或使用自定义类型在将数据加载和转储到数据库时自动为您完成工作。我已经谈到了自定义类型 in this answer .

关于elixir - 如何在 Ecto 模型中使用 uuid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28060582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com