【问题标题】:How to use uuid's with Ecto Models如何将 uuid 与 Ecto 模型一起使用
【发布时间】:2015-01-21 19:24:11
【问题描述】:

我正在尝试将 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

【问题讨论】:

    标签: elixir ecto


    【解决方案1】:

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

    【讨论】:

    • 顺便说一句,我们决定添加一个 Ecto.UUID 类型,它将在即将发布的版本中自动为您执行此操作。
    • Ecto.UUID 已随版本 0.7.0 发布。
    猜你喜欢
    • 2016-02-10
    • 2017-01-15
    • 2012-11-01
    • 1970-01-01
    • 2015-04-19
    • 2011-01-04
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多