简体   繁体   中英

How to input :binary_id in iex command line?

I am writing an application in Elixir with Postgres as the data store. In Ecto, I defined this entity:

defmodule MyModule.User do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  schema "users" do
    field :email, :string
  end

  @fields ~w(email)

  def changeset(data, params \\ %{}) do
    data
    |> cast(params, @fields)
    |> validate_required([:email])
    |> validate_length(:email, max: 128)
    |> unique_constraint(:email)
  end
end

Then, I can save a record in the db in iex -terminal by typing:

iex> user1 = MyModule.User.changeset(%MyModule.User{}, %{email: "foo@bar.com"})
iex> MyModule.Repo.insert!(user1)

Everything runs ok and the record gets saved. But when I try to retrieve it with Repo.get() :

iex> MyModule.Repo.get(MyModule.User, 0)

I get this error:

** (Ecto.Query.CastError) deps/ecto/lib/ecto/repo/queryable.ex:320:
value `0` in `where` cannot be cast to type :binary_id in query:

from u in ScorecardBackend.User,
  where: u.id == ^0,
  select: u

  (elixir) lib/enum.ex:1755: Enum."-reduce/3-lists^foldl/2-0-"/3
  (elixir) lib/enum.ex:1325: Enum."-map_reduce/3-lists^mapfoldl/2-0-"/3

My question: Is there a way to type :binary_id literals in the iex -command line? Thanks a lot!

A binary_id field is represented as a String in Elixir, so you need to pass a String to Repo.get containing the the binary_id , for example:

MyModule.Repo.get(MyModule.User, "0e31998f-503f-4218-a801-c8bb7ff9498b")

The exact length and format of a binary_id field depends on the database. In PostgreSQL, it's a UUID and the default one auto generated is a random UUID. You can see what ID was generated by fetching all the records:

MyModule.Repo.all(MyModule.User)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM