Elixir Postgrex using uuid

Viewed 2972

I am using Postgrex library for my database, and I have the following problem: one of the columns in the database is of type uuid. I am using the UUID module in elixir but whenever I try to persist something to the database I get the following error: Postgrex expected a binary of 16 bytes, got "3c5fda26-ea3b-4c77-8f19-06e106a61eda". I have tried to store it as a plain string but it was not possible as you can see. How should I convert the uuid before persisting it to the database?

3 Answers

I have just found that the UUID module has already a function called UUID.string_to_binary! , and its better to use this one instead of Ectos', as I am not using Ecto at all

UUID is a string, but not a "human readable string". What you see as 3c5fda26-ea3b-4c77-8f19-06e106a61eda is not UUID, it is only one of the possible human readable representations. What you need is to pass direct, internal, UUID representation which in fact is binary of 16 bytes. To parse string form it hexadecimal representation to binary representation you can use Ecto.UUID.dump/1.

Set the type of the field as binary_id in the schema.

For Example:

@primary_key {:id, :binary_id, autogenerate: true}
@derive {Phoenix.Param, key: :id}
schema “companies” do
 field :name, :string
 field :mission_statement, :string

 has_many :managers, EctoUuid.Manager
 timestamps
end
Related